繁体   English   中英

如何对对象数组进行排序以再次保存对象数组

[英]How to sort an array of objects which hold again an array of objects

如何对对象数组进行排序,该对象数组又包含对象数组,我想按其上一个时间戳对其进行排序。

 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'
    }]
  }
]

这可能有效。 它按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); 

使用数组的排序方法:

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

使用您自己的函数进行排序。 它看起来应该像这样:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM