【问题标题】:How to sort an array of objects which hold again an array of objects如何对再次保存对象数组的对象数组进行排序
【发布时间】:2018-07-02 11:13:43
【问题描述】:

如何对包含对象数组的对象数组进行排序,我想按它们的最后一个时间戳对其进行排序。

 var weather = [{
    city: 'New York',
    status: 1,
    response: [{
        name: 'Example', lastTimestamp: '2017-12-19T12:43:14.000Z',
        name: 'Example2', lastTimestamp: '2017-12-19T12:42:14.000Z'
    }]
  },
  {
    city: 'Chicago',
    status: 1,
    response: [{
        name: 'Example', lastTimestamp: '2018-05-10T09:00:00.000Z',
        name: 'Example2', lastTimestamp: '2018-05-10T09:04:00.000Z'
    }]
  }
]

作为回报,我想要这样的排序对象

 var weather = [
  {
    city: 'Chicago',
    status: 1,
    response: [{
        name: 'Example', lastTimestamp: '2018-05-10T09:00:00.000Z',
        name: 'Example2', lastTimestamp: '2018-05-10T09:04:00.000Z'
    }]
  },
  {
    city: 'New York',
    status: 1,
    response: [{
        name: 'Example', lastTimestamp: '2017-12-19T12:43:14.000Z',
        name: 'Example2', lastTimestamp: '2017-12-19T12:42:14.000Z'
    }]
  }
]

【问题讨论】:

  • array.sort 与检查lastTimestamp 的自定义函数一起使用
  • 如果response 中有多个记录,很大程度上取决于排序标准的依据。此外,response 元素格式无效,您可能忘记添加对象符号。也就是说,您应该只使用带有自定义回调的 sort 原型。
  • [name: … 是语法错误,因为 JS 数组不能有命名键,只能有数字键。

标签: javascript arrays sorting javascript-objects


【解决方案1】:

这可能有效。它按city 名称排序,如果它们相等,则按lastTimestamp 排序。

var weather = [
    {
        city: 'New York', status: 1, response: {name: 'Example', lastTimestamp: '2017-12-19T12:43:14.000Z'}
    },
    {
        city: 'Chicago', status: 1, response: {name: 'Example', lastTimestamp: '2018-05-10T09:00:00.000Z'}
    },
    {
        city: 'New York', status: 1, response: {name: 'Example', lastTimestamp: '2017-12-20T12:43:14.000Z'}
    },
    {
        city: 'Chicago', status: 1, response: {name: 'Example', lastTimestamp: '2018-05-09T09:00:00.000Z'}
    }
];

weather.sort(function(a,b){
    return a.city>b.city ? 1 :
            a.city<b.city ? -1 : new Date(a.response.lastTimestamp)-new Date(b.response.lastTimestamp)
})

console.log(weather);

【讨论】:

    【解决方案2】:

    在您自己的函数中使用排序。它应该是这样的:

    weather.sort( (a,b) => {
        return new Date(b.response.lastTimestamp) - new Date(a.response.lastTimestamp)
    });
    

    【讨论】:

    • 不需要getTime()
    【解决方案3】:

    使用Array的sort方法:

    weather.sort(function(obj1, obj2){
       return obj1.response.lastTimestamp < obj2.response.lastTimestamp ? 1 : -1;
    });
    

    【讨论】:

      猜你喜欢
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多