我正在寻找一种将具有相同日期的对象合并为一个对象的方法。 感谢您的帮助。
const data = [
{ date: '1 Day', green: 35 },
{ date: '2 Day', green: 64 },
{ date: '3 Day', green: 46 },
{ date: '4 Day', green: 87 },
{ date: '5 Day', green: 32 },
{ date: '1 Day', red: 85 },
{ date: '2 Day', red: 55 },
{ date: '3 Day', red: 37 },
{ date: '1 Day', orange: 4 },
{ date: '2 Day', orange: 44 },
{ date: '3 Day', orange: 9 },
{ date: '4 Day', orange: 88 },
{ date: '5 Day', orange: 60 },
{ date: '6 Day', orange: 15 },
];
所需的输出。
const data = [
{ date: '1 Day', green: 35, red: 85, orange: 4 },
{ date: '2 Day', green: 64, red: 55, orange: 44 },
{ date: '3 Day', green: 46, red: 37, orange: 9 },
{ date: '4 Day', green: 87, orange: 88 },
{ date: '5 Day', green: 32, orange: 60 },
{ date: '6 Day', orange: 15 },
]
答案 0 :(得分:0)
您可以创建一个哈希值,以使用key
运算符将不同的对象与相同的spread
(在这种情况下为日期)组合在一起,同时遍历数组中的对象
// reusable function to reduce object arrays
// `key` - <String>; object property name to combine objects by
// `data` - <Array>, of objects
function reduceObjectArr(key, data) {
const hash = []
for (let el of data) {
const keyValue= el[key]
hash[keyValue] = { ...(hash[keyValue] || {} ), ...el }
}
return Object.values(hash)
}
// current usage
const data = [
{ date: '1 Day', green: 35, red: 85, orange: 4 },
{ date: '2 Day', green: 64, red: 55, orange: 44 },
{ date: '3 Day', green: 46, red: 37, orange: 9 },
{ date: '4 Day', green: 87, orange: 88 },
{ date: '5 Day', green: 32, orange: 60 },
{ date: '6 Day', orange: 15 },
]
const result = reduceObjectArr('date', data)
console.log(result)