0

示例数组如下:

   var aa = [{date: "sep", data:[1,2,3]}, {date: "oct", data:[4,5,6]}];
   var bb = [{date: "oct", data:[1,2,3]}, {date: "nov", data:[40,50,60]}, {date: "dec", data:[41,51,61]}];

合并后的结果应该是这样的:

  var mergedArray =
 [
{date: "sep", data:[1,2,3]},
{date: "oct", data:[4,5,6,1,2,3]},
{date: "nov", data:[40,50,60]},
{date: "dec", data:[41,51,61]}
]
4

3 回答 3

2

您可以使用.reduce()将两个对象数组减少为一个对象,其中对象的键是 each date,并且 eachdate存储对整个对象的引用。但是,如果出现重复日期(即:该日期已存在于累积对象中),您可以将数组改为.concat()已存在的数组。最后,使用我们最初创建的日期顺序数组,您可以将生成的对象映射到合并对象的数组中,如下所示:

const aa = [{date: "sep", data:[1,2,3]}, {date: "oct", data:[4,5,6]}];
const bb = [{date: "oct", data:[1,2,3]}, {date: "nov", data:[40,50,60]}, {date: "dec", data:[41,51,61]}];

const merged = [...aa, ...bb];
const order = [...new Set(merged.map(({date}) => date))];

const mergedObj = merged.reduce((acc, {date, data, ...rest }) => {
  acc[date] = acc[date] || {date, ...rest, data: []};
  acc[date].data = acc[date].data.concat(data);
  return acc;
}, {});

const res = order.map(key => mergedObj[key]);
console.log(res);

于 2019-09-28T14:16:44.110 回答
0

您可以在一个 for 循环中执行此操作。

  
  const aa = [{date: "sep", data:[1,2,3]}, {date: "oct", data:[4,5,6]}];
    const bb = [{date: "oct", data:[1,2,3]}, {date: "nov", data:[40,50,60]}, {date: "dec", data:[41,51,61]}];
    
    let tempArr = aa;
    
bb.forEach(rec => { 
    let findIndex = tempArr.findIndex(obj => obj.date == rec.date);
    if(findIndex==-1){
       tempArr.push(rec);
       } else {
      tempArr[findIndex].data = tempArr[findIndex].data.concat(rec.data);
       }
    });
    console.log(tempArr);

于 2019-09-28T14:39:11.700 回答
0

您可以采用Map和分组date并获取新对象作为结果集。

var array1 = [{ date: "sep", data: [1, 2, 3] }, { date: "oct", data: [4, 5, 6] }],
    array2 = [{ date: "oct", data: [1, 2, 3] }, { date: "nov", data: [40, 50, 60] }, { date: "dec", data: [41, 51, 61] }],
    result = Array.from(
        [...array1, ...array2].reduce(
            (m, { date, data }) => m.set(date, [...(m.get(date) || []), ...data]),
            new Map
        ),
        ([date, data]) => ({ date, data })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

于 2019-09-28T15:23:37.547 回答