javascript,lodash: - 如何对象中包含对象的对象数组

时间:2017-05-09 09:03:13

标签: javascript arrays sorting object lodash

var a = [
   {  
        "subObj1": {  
            "key1":10722905,
            "key2":"0080817626"
        },
        "outerKey1":"abcd",
        "outerKey2":"defg"
    },
    {  
        "subObj1": {  
            "key1":123456,
            "key2":"0987654"
        },
        "outerKey1":"pqrs",
        "outerKey2":"ased"
    }
]

我需要分别使用key1和outerkey1对这个对象数组进行排序。这个逻辑已经实现了。

_.sortBy(a,'outerKey1') - >这工作正常。

_.sortBy(a,'key1') - >这不起作用。

_.sortBy(a,'subObj1.key1') - >这也行不通。

有没有办法使用lodash _.sortBy函数使用key1或key2等对象的内部键对这个对象数组进行排序?

1 个答案:

答案 0 :(得分:1)

仅使用JavaScript,您可以使用 Array.prototype.sort() 以及自定义回调功能:

var sorted = arr.sort(function(a, b) {
  a.subObj1.key1 - b.subObj1.key1
});

<强>演示:

var arr = [{
    "subObj1": {
      "key1": 10722905,
      "key2": "0080817626"
    },
    "outerKey1": "abcd",
    "outerKey2": "defg"
  },
  {
    "subObj1": {
      "key1": 123456,
      "key2": "0987654"
    },
    "outerKey1": "pqrs",
    "outerKey2": "ased"
  }
];

var sorted = arr.sort(function(a, b) {
  a.subObj1.key1 - b.subObj1.key1
});

console.log(sorted);

修改

如果您希望使用lowdash进行此操作,则可以将_.sortBy()与自定义排序功能结合使用:

var customSorter = function(obj) {
  return obj.subObj1.key1;
};
var sorted = _.sortBy(arr, customSorter);

<强>演示:

var arr = [{
    "subObj1": {
      "key1": 10722905,
      "key2": "0080817626"
    },
    "outerKey1": "abcd",
    "outerKey2": "defg"
  },
  {
    "subObj1": {
      "key1": 123456,
      "key2": "0987654"
    },
    "outerKey1": "pqrs",
    "outerKey2": "ased"
  }
];

var customSorter = function(obj) {
  return obj.subObj1.key1;
};
var sorted = _.sortBy(arr, customSorter);

console.log(sorted);
<script src="http://underscorejs.org/underscore-min.js"></script>