如何使用Javascript对此JSON进行排序?

时间:2018-06-15 09:26:41

标签: javascript json node.js sorting

这是我的JSON文件数据。

{"434762882136408065":{"hacksilver":1500,"lastDaily":"06/15/2018","username":"Bader56"},"419738969530433548":{"hacksilver":"10009000","lastDaily":"NOT COLLECTED","username":"Robotos"}}

我希望它能让最富有的用户登录到最富有的用户 像

  
      
  1. ROBOTOS:10009000
  2.   
  3. Bader56:1500
  4.   

我试过

Object.keys(userData).forEach(user => {
        console.log(userData[user].username+': '+userData[user].hacksilver);
    });

但是它首先记录了Bader,我也试过.reverse()但是如果第三个人在这里那就一样

2 个答案:

答案 0 :(得分:1)

您可以先sort()数组。

使用Object.values将对象转换为数组。使用sort()重新排序数组。使用forEach循环遍历排序的数组。



let userData = {"434762882136408065":{"hacksilver":1500,"lastDaily":"06/15/2018","username":"Bader56"},"419738969530433548":{"hacksilver":"10009000","lastDaily":"NOT COLLECTED","username":"Robotos"}}

Object.values(userData).sort((a, b) => b.hacksilver - a.hacksilver)
                       .forEach(o => {
                            console.log(o.username + ': ' + o.hacksilver);
                       })




如果您的nodejs不支持Object.values,您可以使用Object.keys作为:



let userData = {"434762882136408065":{"hacksilver":1500,"lastDaily":"06/15/2018","username":"Bader56"},"419738969530433548":{"hacksilver":"10009000","lastDaily":"NOT COLLECTED","username":"Robotos"}}

Object.keys(userData).sort((a, b) => userData[b].hacksilver - userData[a].hacksilver)
                     .forEach(o => {
                          console.log(userData[o].username + ': ' + userData[o].hacksilver);
                     })




文档:sort()forEach()

答案 1 :(得分:1)

将原始对象转换为数组,因此可以对其使用sort方法,然后按任何条件对其进行排序:

const dataObj = {"434762882136408065":{"hacksilver":1500,"lastDaily":"06/15/2018","username":"Bader56"},"419738969530433548":{"hacksilver":"10009000","lastDaily":"NOT COLLECTED","username":"Robotos"}};

// convert object to array
const dataArr = Object.keys(dataObj).map(key => dataObj[key]);

// sort it by hacksilver value
const sorted = dataArr.sort((a,b) => {
    return Number(b.hacksilver) - Number(a.hacksilver) 
});

console.log(sorted);