Skip to content Skip to sidebar Skip to footer

Sort Json By Array Key Value

I have an example JSON file consisting of: { '119996306407030785': { 'duel': { 'class': 'mage', 'totalDamage': 64, 'wins': 5,

Solution 1:

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

Solution 2:

To sort objects by duel.wins try this

functionsortByWins(obj) {
    returnObject.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;
    }, {});
}

Solution 3:

Loop over the object using the keys:

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

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

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

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

Post a Comment for "Sort Json By Array Key Value"