I have this structure:
var example=[0,{ "3":4 , "6":1 , "11":2 }];
I would like to transform this into
[0,{ "6":1 , "11":2 , "3":4 }]
based on the number on the right (ascendant): 4, 1, 2
becomes 1 ,2, 4
.
I have this structure:
var example=[0,{ "3":4 , "6":1 , "11":2 }];
I would like to transform this into
[0,{ "6":1 , "11":2 , "3":4 }]
based on the number on the right (ascendant): 4, 1, 2
becomes 1 ,2, 4
.
Infact order in objects are not guaranteed in JavaScript, you need to use an Array to have similar result:
function sortObjectByValue(obj) {
var result = [];
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push({
'key': key,
'value': obj[key]
});
}
}
arr.sort(function(a, b) {
return a.value - b.value;
});
return result; // returns array
}
>>>var obj = { "3":4 , "6":1 , "11":2 };
>>>console.log(sortObjectByValue(obj))
//[Object { key="6", value=1}, Object { key="11", value=2}, Object { key="3", value=4}]
I will suggest also if you find your self dealing a lot with data-structure and need advanced methods check Underscore