I have below type of object, I want to sort on based on sort_value of object. I tried below solution but it gives me error.
var data = {
7:{
name: 'Test1',
city: 'Mohali',
sort_order: -1
},
9:{
name: 'Test2',
city: 'Delhi',
sort_order: 2
},
10:{
name: 'Test3',
city: 'Chicago',
sort_order: 0
}
}
I Tried this one solution
data.sort(function(a, b) {
return parseFloat(a.sort_order) - parseFloat(b.sort_order);
});
Gives me error like this
Uncaught TypeError: data.sort is not a function
Expected Output
var Expectedop = {
7:{
name: 'Test1',
city: 'Mohali',
sort_order: -1
},
10:{
name: 'Test3',
city: 'Chicago',
sort_order: 0
},
9:{
name: 'Test2',
city: 'Delhi',
sort_order: 2
}
}
sort is an in-built method available on Arrays.
What you can do is use Object.keys(data) which will give you array of keys ([7,9,10]) and sort it using the sort function. When you have the keys sorted in the array, you can use them to update sort_order in the data object.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys