是否在JavaScript中使用新的键名合并对象数组?

cigdeys3  于 2023-01-07  发布在  Java
关注(0)|答案(3)|浏览(119)

任何帮助都将不胜感激。
我有一个数组(A),其中包含3个对象数组。

A = [
[{date: '2022-12-05', value: 10.6},{date: '2022-12-06', value: 5.6},{date: '2022-12-07, value: 8.6}],
[{date: '2022-12-05', value: 4.2},{date: '2022-12-06', value: 12.3},{date: '2022-12-07, value: 9.5}],
[{date: '2022-12-05', value: 5.6},{date: '2022-12-06', value: 9.8},{date: '2022-12-07, value: 7.8}]
]

从这个数组(A)中,我需要得到一个数组(B),它将包含合并/连接的数组,这些数组具有新的/重命名的对象键(value1,value2,value3),格式如下:

B =  [
{date: '2022-12-05', value1: 10.6, value2: 4.2, value3: 5.6},
{date: '2022-12-06', value1: 5.6, value2: 12.3, value3: 9.8},
{date: '2022-12-07', value1: 8.6, value2: 9.5, value3: 7.8}
]

第一个数组(A)的长度可以变化(1/2/3或更大),这就是为什么我努力寻找一个动态/有效的解决方案。
多谢了

ioekq8ef

ioekq8ef1#

您可以使用Map并收集所有值。

const
    data = [[{ date: '2022-12-05', value: 10.6 }, { date: '2022-12-06', value: 5.6 }, { date: '2022-12-07', value: 8.6 }], [{ date: '2022-12-05', value: 4.2 }, { date: '2022-12-06', value: 12.3 }, { date: '2022-12-07', value: 9.5 }], [{ date: '2022-12-05', value: 5.6 }, { date: '2022-12-06', value: 9.8 }, { date: '2022-12-07', value: 7.8 }]],
    result = Array.from(
        data
            .flat()
            .reduce((m, { date, value }) => m.set(date, [...m.get(date) || [], value]), new Map),
        ([date, values]) => values.reduce((o, v, i) => ({ ...o, [`value${i + 1}`]: v }), { date })
    )
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
1zmg4dgp

1zmg4dgp2#

您可以使用map()reduce()函数:

const A = [
  [{date: '2022-12-05', value: 10.6},{date: '2022-12-06', value: 5.6},{date: '2022-12-07', value: 8.6}],
  [{date: '2022-12-05', value: 4.2},{date: '2022-12-06', value: 12.3},{date: '2022-12-07', value: 9.5}],
  [{date: '2022-12-05', value: 5.6},{date: '2022-12-06', value: 9.8},{date: '2022-12-07', value: 7.8}]
];

const B = A.reduce((acc, curr) => {
  curr.forEach(item => {
    const existingItem = acc.find(i => i.date === item.date);
    if (existingItem) {
      existingItem[`value${A.indexOf(curr) + 1}`] = item.value;
    } else {
      acc.push({
        date: item.date,
        [`value${A.indexOf(curr) + 1}`]: item.value
      });
    }
  });
  return acc;
}, []);

console.log(B);
lokaqttq

lokaqttq3#

我可以建议一个更简单的数据结构吗?不要以'value1,' value2',... 'valueN'的形式对值进行编号,您可以使用每个日期的值数组,这也会使转换更容易一些:

const A = [
  [{date: '2022-12-05', value: 10.6},{date: '2022-12-06', value: 5.6},{date: '2022-12-07', value: 8.6}],
  [{date: '2022-12-05', value: 4.2},{date: '2022-12-06', value: 12.3},{date: '2022-12-07', value: 9.5}],
  [{date: '2022-12-05', value: 5.6},{date: '2022-12-06', value: 9.8},{date: '2022-12-07', value: 7.8}]
]

//Flatten Array
const Af = A.flat();

//Group by date
const B = Af.reduce((acc, cur) => {
  acc[cur['date']] = acc[cur['date']] ? [...acc[cur['date']], cur.value] : [cur.value]
  return acc;
}, {});

console.log(B);

相关问题