我的服务器上有这个JSON文件:
{"1504929411112":{"name":"user1","score":"10"},"1504929416574":{"name":"2nduser","score":"14"},"1504929754610":{"name":"usr3","score":"99"},"1504929762722":{"name":"userfour","score":"40"},"1504929772310":{"name":"user5","score":"7"}}
假设我已经解析了这个文件:
var json = JSON.parse(getJSONFile());
我现在如何按json
属性对score
变量中的每个对象进行排序?
由于json
不是数组,所以数组排序函数都不适用于我。
答案 0 :(得分:2)
由于这些是对象的属性,因此它们的顺序通常是未知的,不能保证。要按某些内部属性对它们进行排序,首先必须将Object更改为Array,例如:
const json = JSON.parse(getJsonFile());
const jsonAsArray = Object.keys(json).map(function (key) {
return json[key];
})
.sort(function (itemA, itemB) {
return itemA.score < itemB.score;
});
有关更多信息,请参阅:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
答案 1 :(得分:2)
var ob = { "fff": { "name": "user1", "score": "10" }, "bbbb": { "name": "user4", "score": "14" }, "dddd": { "name": "user2", "score": "99" }, "cccc": { "name": "user5", "score": "40" }, "aaaa": { "name": "user3", "score": "7" } };
Object.keys(ob).map(key => ({ key: key, value: ob[key] })).sort((first, second) => (first.value.name < second.value.name) ? -1 : (first.value.name > second.value.name) ? 1 : 0 ).forEach((sortedData) => console.log(JSON.stringify(sortedData)));