通过嵌套对象的属性仅对数组内的父对象进行排序

时间:2017-05-19 13:36:06

标签: javascript jquery arrays sorting nested

[["2017-05-01","2017-05-02"], ["2017-05-3","2017-05-04"], ....]

我在Array中有一个对象集合,我需要根据嵌套对象的属性名称对该对象集合进行排序,将其拆分为“ - ”(我要查找的属性是address.name)。所以上面分裂后是1和2。所以我想要实现的是一个函数,它将返回一个排序的对象数组,如下面的

{
  "services": [{
    "id": "b1",
    "address": {
      "location_id": "loc_b1",
      "name": "hunupitiya-2",
      "lon": "",
      "lat": ""
    },
    "size": [1700]
  },{
    "id": "b2",
    "address": {
      "location_id": "loc_b2",
      "name": "kelaniya-1",
      "lon":"" ,
      "lat":"" 
    },
    "size": [2889]
  }]
} 

我有31个对象,我也有没有“ - ”的对象,所以我尝试从小到大编号一次,然后以任何顺序编号。我已经创建了一个jsfiddle来尝试它。

https://jsfiddle.net/cbjosk3g/

1 个答案:

答案 0 :(得分:0)

您可以使用带有sort函数的标准Array#sort,该函数将值拆分并获取数组的第二部分。

var $scope = { services: [{ id: "b1", address: { location_id: "loc_b1", name: "hunupitiya-2", lon: "", lat: "" }, size: [1700] }, { id: "b2", address: { location_id: "loc_b2", name: "kelaniya-1", lon: "", lat: "" }, size: [2889] }] };

$scope.services.sort(function (a, b) {
    return a.address.name.split('-')[1] - b.address.name.split('-')[1];
});

console.log($scope);
.as-console-wrapper { max-height: 100% !important; top: 0; }