这是我的JSON文件数据。
{"434762882136408065":{"hacksilver":1500,"lastDaily":"06/15/2018","username":"Bader56"},"419738969530433548":{"hacksilver":"10009000","lastDaily":"NOT COLLECTED","username":"Robotos"}}
我希望它能让最富有的用户登录到最富有的用户 像
- ROBOTOS:10009000
- Bader56:1500
醇>
我试过
Object.keys(userData).forEach(user => {
console.log(userData[user].username+': '+userData[user].hacksilver);
});
但是它首先记录了Bader,我也试过.reverse()
但是如果第三个人在这里那就一样
答案 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);
})

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