As mentioned in numerous comments, you don't "sort" an object. Sort implies order, implies a collection, implies a data structure.
So first thing is first, you need an array of the objects. So extract them into an array by iterating over the keys. Then use Array.sort
with a custom comparator.
var objectsToSort = {
"166":
{
"name":{"name":"name","val":"matt","order":""},
"props":{"name":"props","val":"1","order":""}
},
"147":
{
"name":{"name":"name","val":"chris","order":""},
"props":{"name":"props","val":"4","order":""}
}
}
var objects = Object.keys(objectsToSort).map(function (key) {
return objectsToSort[key];
});
objects.sort(function (a, b) {
return a.val - b.val;
});
I noticed that val
is a string representation of a number. If you want a numeric sort, either change them to pure integers or change the sort function above to use a parseInt
:
objects.sort(function (a, b) {
return parseInt(a.val, 10) - parseInt(b.val, 10);
});
I prefer to change the actual data than the function because that parsing will run twice per comparison and sorting usually N * log(n). So it will run 2(N * log(n)).