我是一个对象数组。每个对象都有一个date属性和一个string属性。我也有一个空数组。我无法弄清楚根据最早的日期到最新的日期推送字符串的逻辑。
const oldToNew = []
for (const baseId in results[key][test]) {
// log the array of objects
//example [{string: 'test', date: '2019-03-04T10:36:37.206000Z'}, {string: 'test1', date: '2019-03-010T10:36:37.206000Z'}]
console.log(results[key][test][baseId])
results[key][test][baseId].forEach(element => {
});
}
// I want the value to be [test, test1]
答案 0 :(得分:1)
使用Array.sort将每个Object的date
属性与其之前的对象进行比较-然后使用Array.map返回所有项“ string
”属性的数组。
更新,无需parse
日期时间戳。
const items = [{string: 'test4', date: '2019-03-04T10:36:37.206000Z'}, {string: 'test1', date: '2019-03-10T10:36:37.206000Z'}, {string: 'test2', date: '2019-03-09T10:36:37.206000Z'}, {string: 'test3', date: '2019-03-07T10:36:37.206000Z'}]
const strings = items
.sort((a, b) => b.date > a.date)
.map(({ string }) => string)
console.log(strings)
答案 1 :(得分:1)
您需要使用sort
对初始数组进行排序,然后使用map
提取字符串
类似这样的东西:
array.sort((a, b) => a.date < b.date).map(el => el.string);