首页 文章

Javascript =>按日期将数组元素相互匹配

提问于
浏览
0

我有一个超过50个对象的数组 . 这个数组是concat(ing)两个数组的结果 . 此数组中的元素是对象,每个对象都具有关键字'date',日期字符串格式为:

`"2017-03-31T11:30:00.000Z"`

并用文字键入' Headers ' . 所以我有这样的元素:

[
    {date: "2017-03-31T11:30:00.000Z", caption: "text_1"},
    {date: "2016-03-31T11:30:00.000Z", caption: "text_2"},
    {date: "2016-03-31T11:30:00.000Z", caption: "text_3"},
    {date: "2017-03-31T11:30:00.000Z", caption: "text_4"}
]

在Ruby中,我知道更好更深入,您可以在数组中映射元素并返回新的元素并通过if语句返回条件 . 我想知道在JS中是否有类似的东西,我正在循环遍历数组并将每个元素与其他元素匹配,但它不是最高效的方式 . 我想做的事情如下:

let newArray = myArray.map( (a,b) => { if (a.date === b.date) { return {text1: a.caption, text2: b.caption}}});

结果将是:

[
  {text1: "text_1", text2: "text_4"},
  {text1: "text_2", text2: "text_3"}
]

这样的事情,优雅和高效的东西存在吗?

谢谢...

1 回答

  • 1

    你的问题的答案是:
    不,Javascript中没有任何功能可以按照您的要求优雅地完成您想要的功能(不确定性能) .

    对于您的特定用例,我只需创建一个使用日期作为键的新对象并收集不同的 Headers ,然后将该对象转换为数组:

    const collected = {};
    
    myArray.forEach((entry) => {
        if (entry.date in collected) {
            collected[entry.date].text2 = entry.caption;
        } else {
            collected[entry.date] = { text1: entry.caption };
        }
    });
    
    const newArray = Object.keys(collected).map(key => collected[key]);
    

相关问题