我有一个对象。
[
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
]
如何使用下划线按 ASC 数字按 mesafe
字段顺序对该对象进行排序?
最佳答案
你可以考虑
{
"home1": {
"mesafe":11
}
}
作为
{
"home1": {
"mesafe":11
},
// fakes
"home2": {},
"home3": {}...
}
现在要排序的值可以描述为:
从子对象中获取所有 mesafe
属性的值并将它们相加(如果该属性存在)。
所以可以使用_.reduce
来实现。
var list = [
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
];
var sortedList = _.sortBy(list, function(item) {
// For each item, we acts as there not only have one attribute "homex", but there's many other like "homey : {}".
var res = _.reduce(item, function(res, sub) {
// So we can the again use reduce to iterate through them, and add the value if mesafe exist.
return (sub.mesafe == null) ? res : res + sub.mesafe;
}, 0);
return res;
});
console.log(sortedList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
关于javascript - 下划线多维排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31762571/