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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…