Reputation: 2944
I need to sort associative array by value (using "position" value as shown below). I tried by converting into array. It is working fine. But I wanted to know, Is there any other way of doing it?
{
"CAB":{
name:CBSSP,
position:2
},
"NSG":{
name:NNSSP,
position:3
},
"EQU":{
name:SSP,
position:1
}
}
Upvotes: 0
Views: 62
Reputation: 1322
You could also try:
Object.keys(o).map(function(key){return o[key];})
.sort(function(p, c){return p.position - c.position})
Upvotes: 1
Reputation: 386570
You can use an order array for the ordered reference to the object. You need a correction of position, because arrays are zero based.
var object = { "CAB": { name: 'CBSSP', position: 2 }, "NSG": { name: 'NNSSP', position: 3 }, "EQU": { name: 'SSP', position: 1 } },
order = [];
Object.keys(object).forEach(function (k) {
return order[object[k].position - 1] = k;
});
document.write('<pre>' + JSON.stringify(order, 0, 4) + '</pre>');
Upvotes: 0
Reputation: 64526
There is no associative array in JavaScript, what you have is an object, with properties CAB
, NSG
and EQU
.
Object properties can't guarantee a set order, so the solution is to use an array of objects because arrays do indeed guarantee the order.
Upvotes: 0