I have an object that looks like the one below. How can I sort something like this based on a common property within nested object. The output I expect is for player2 to come first based on the higher score.
My challenge is in accessing the property of each object to sort.
Here is what I had in mind and tried but it didn't do the sorting.
Object.keys(data).sort(function(p1, p2){
return p1.score - p2.score;
}).forEach(function(key) {
var value = data[key];
delete data[key];
data[key] = value;
});
My data
var data =
{
player1:
{ score: 4,
cards: 6 },
player2:
{ score: 6,
cards: 4}
}
Sort-Object uses the Property parameter with a hash table to specify the property names and sort orders. The Property parameter is sorted by two properties, Status in descending order and DisplayName in ascending order. Status is an enumerated property. Stopped has a value of 1 and Running has a value of 4.
To sort the keys of an object:Use the Object. keys() method to get an array of the object's keys. Call the sort() method on the array. Call the reduce() method to get an object with sorted keys.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With