This my JSON file data.
{"434762882136408065":{"hacksilver":1500,"lastDaily":"06/15/2018","username":"Bader56"},"419738969530433548":{"hacksilver":"10009000","lastDaily":"NOT COLLECTED","username":"Robotos"}}
And i want it to log users by richest to not richest like
- ROBOTOS: 10009000
- Bader56: 1500
i tried
Object.keys(userData).forEach(user => {
console.log(userData[user].username+': '+userData[user].hacksilver);
});
but its logging Bader at first place, Also i tried .reverse()
but it the same if there third person here
You can sort()
the array first.
Use Object.values
to convert the object into an array. use sort()
to reorder the array. Use forEach
to loop thru the sorted array.
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); })
If your nodejs does not support Object.values
you can use Object.keys
as:
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); })
Convert the original object to array, so you could use sort
method on it, and then sort it by any criteria:
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);
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.