按数组键值排序JSON

时间:2016-03-29 17:28:49

标签: javascript json node.js

我有一个示例JSON文件,包含:

{
    "119996306407030785": {
        "duel": {
            "class": "mage",
            "totalDamage": 64,
            "wins": 5,
            "losses": 2
        },
        "weather": {
            "location": "46544"
        }
    },
    "119333755579138048": {
        "duel": {
            "class": "rogue",
            "totalDamage": 35,
            "losses": 1,
            "wins": 2
        },
        "weather": {
            "location": "95825"
        }
    },
    "112006834713329664": {
        "duel": {
            "totalDamage": 33,
            "losses": 1,
            "wins": 7
        }
    }
}

119996306407030785是一个userID。我希望按照所有用户的最高决定权对#"前5"概念

我想用上面的JSON输出的是:

112006834713329664 - 7 wins   
119996306407030785 - 5 wins  
119333755579138048 - 2 wins 

我在谷歌搜索时看到了与此问题相近的多个问题,但无法找到与我的设置类似的JSON。

考虑到我的用户ID是如何设置的,这是否可行?&他们有多随机?如果是这样,怎么办呢?请注意,我不仅需要返回胜利数,还需要返回与该获胜金额相关的用户ID。即使有几十个用户ID,我也只想返回前5名。

3 个答案:

答案 0 :(得分:0)

var data = { "119996306407030785": { "duel": { "class": "mage", "totalDamage": 64, "wins": 5, "losses": 2 }, "weather": { "location": "46544" } }, "119333755579138048": { "duel": { "class": "rogue", "totalDamage": 35, "losses": 1, "wins": 2 }, "weather": { "location": "95825" } }, "112006834713329664": { "duel": { "totalDamage": 33, "losses": 1, "wins": 7 } } } 

var a = Object.keys(data).map(e => ({id: e, wins: data[e].duel.wins}))
        .sort((a, b) => b.wins - a.wins);

document.write('<pre>' + JSON.stringify(a, 0, 2) + '</pre>')

答案 1 :(得分:0)

要按duel.wins对对象进行排序,请尝试使用

function sortByWins(obj) {
    return Object.keys(obj).sort(function(i, j) {
        return obj[i].duel.wins - obj[j].duel.wins;
    }).reduce(function (result, key) {
        result[key] = obj[key];
        return result;
    }, {});
}

答案 2 :(得分:0)

使用键遍历对象:

Object.keys(obj).reduce(function (p, c) {

  // return an array of winner objects
  return p.concat({ id: c, wins: obj[c].duel.wins });
}, []).sort(function (a, b) {

  // sort the objects by wins
  return a.wins < b.wins;
}).forEach(function (el) {

  // Display the information
  console.log([el.id,'-',el.wins,'wins'].join(' '));
});