Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

javascript - 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} 
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...