以下是我的JavaScript对象。
{
"014b9d42":{
"notification": 0,
"userName": "adam"
},
"02f5b60e": {
"notification": 3,
"userName": "jake"
},
"1281d8fb": {
"notification": 1,
"userName": "eomer"
},
"12a2a564": {
"notification": 0,
"userName": "bella"
}
}
我想根据通知值对上述对象进行排序。我怎么能用下划线js来做呢?
答案 0 :(得分:3)
正如@adeneo所指出的,order in objects is not guaranteed。您需要将对象转换为数组,然后根据notification
属性进行排序。
var jsonObj = JSON;
var arr = [];
for (var key in jsonObj) {
if (jsonObj.hasOwnProperty(key)) {
var o = jsonObj[key];
arr.push({ id: key, notification: o.notification, userName: o.userName });
}
}
arr.sort(function(obj1, obj2) {
return obj1.notification - obj2.notification;
});
答案 1 :(得分:1)
您提供的JSON不是列表。因此无法对其进行排序。如果这是一个列表,那么您可以使用以下代码:
var a = [
{"014b9d42": {
"notification": 0,
"userName": "adam"
}},
{"02f5b60e": {
"notification": 3,
"userName": "jake"
}},
{"1281d8fb": {
"notification": 1,
"userName": "eomer"
}},
{"12a2a564": {
"notification": 0,
"userName": "bella"
}}
];
var sorted = _.sortBy(a, function(item) {
var key = [Object.keys(item)[0]];
return item[key]['notification'];
});
console.log(sorted);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>