简体   繁体   中英

Sort JSON by array key value

I have an example JSON file consisting of:

{
    "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 is a userID. I'd like to sort the return by the highest duel.wins of all users for a "top 5" concept.

The output I would like with the above JSON would be:

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

I've seen multiple questions close to this one while Googling, but can't find any that have JSON similar to my setup.

Is this possible considering how my userID's are setup & how random they are? If so, how can it be done? Please take note that I would not only need the return of the # of wins, but also the userID correlating to that win amount. I would also like to only return the top 5 even if there are dozens of userID's.

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

To sort objects by duel.wins try this

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

Loop over the object using the keys:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM