Js lodash按更深的领域排序

时间:2014-12-17 13:23:53

标签: javascript lodash

我有一个对象数组,我想按更深的字段排序。我怎么能这样做?

var array =    
   {
     "id": 27,
     "name": "La Primita Product",
     "lottery": {
        "id": 1,
        "name": "La Primitiva",
        "jackpotAmount": 10000,
      }
   },
    {
     "id": 28,
     "name": "La Primita Product",
     "lottery": {
        "id": 1,
        "name": "La Primitiva",
        "jackpotAmount": 10000,
    }

我如何按lottery.jackpot金额排序?

1 个答案:

答案 0 :(得分:17)

_.sortBy,您可以将回调作为第二个参数传递,如此

var array = [{
  "id": 27,
  "name": "La Primita Product",
  "lottery": {
    "id": 1,
    "name": "La Primitiva",
    "jackpotAmount": 10000,
  }
}, {
  "id": 28,
  "name": "La Primita Product",
  "lottery": {
    "id": 1,
    "name": "La Primitiva",
    "jackpotAmount": 10,
  }
}];

array = _.sortBy(array, function (el) {
  return el.lottery.jackpotAmount;
});

console.log(array);
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>