Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort objects of objects by nested property

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} 
    }
like image 524
mo_maat Avatar asked Jan 23 '18 19:01

mo_maat


People also ask

How do you sort an object property?

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.

Can I sort the object keys JavaScript?

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.


1 Answers

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);
like image 162
Nina Scholz Avatar answered Sep 18 '22 07:09

Nina Scholz