【发布时间】: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