如何对对象数组进行排序,该对象数组又包含对象数组,我想按其上一个时间戳对其进行排序。
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'
}]
}
]
答案 0 :(得分: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);
答案 1 :(得分:0)
使用数组的 sort 方法:
weather.sort(function(obj1, obj2){
return obj1.response.lastTimestamp < obj2.response.lastTimestamp ? 1 : -1;
});
答案 2 :(得分:0)
对您自己的函数使用排序。它应该看起来像这样:
weather.sort( (a,b) => {
return new Date(b.response.lastTimestamp) - new Date(a.response.lastTimestamp)
});