我有一个对象。

[
    { "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": {}...
}


现在可以将要排序的值描述为:

从subObject获取所有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/

10-10 22:00
查看更多