按嵌套属性对对象进行排序 [英] Sort objects of objects by nested property

查看:57
本文介绍了按嵌套属性对对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面的对象.我如何基于嵌套对象内的公共属性对此类内容进行排序.我期望基于较高的分数,玩家2的输出排在第一位.

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

我的数据

var data =
    { 
      player1:
       { score: 4,
         cards: 6 },
      player2:
       { score: 6,
         cards: 4} 
    }

推荐答案

您需要使用对象(而不是键的属性)对数据进行排序,然后必须还原该数据,因为您需要使用降序排序.

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

这篇关于按嵌套属性对对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆