Sort objects of objects by nested property
You need to sort the data with the object, not with a key's property and then it has to be reverted, because you need a descending sort.
return data[b].score - data[a].score;
// ^^^^^^^ ^^^^^^^ object
// ^ ^ descending
I suggest to use an empty object and insert the properties by the ordered keys.
var data = { player1: { score: 4, cards: 6 }, player2: { score: 6, cards: 4 } },
sorted = {};
Object
.keys(data).sort(function(a, b){
return data[b].score - data[a].score;
})
.forEach(function(key) {
sorted[key] = data[key];
});
console.log(sorted);
Here is one line functional approach using Object.entries()
, Array.prototype.sort()
and Object.fromEntries
method. Before sorting you need to make the object an array by using Object.entries()
method. It returns array of key-value pair of the given object. Then sort the array in descending order by the score. At last, use Object.fromEntries()
method to transform the key-value pair into an object.
const data = {
player1: { score: 4, cards: 6 },
player2: { score: 6, cards: 4 },
};
const ret = Object.fromEntries(
Object.entries(data).sort((x, y) => y[1].score - x[1].score)
);
console.log(ret);