gpt4 book ai didi

javascript - 将多维对象数组缩减为单个对象数组

转载 作者:行者123 更新时间:2023-12-03 16:49:59 24 4
gpt4 key购买 nike

我有这个多维对象数组 -

const initialArray = [
{
name: 'aaa',
value:[{id:1, data:1}, {id:2, data:2}, {id:3, data:3}]
},
{
name: 'bbb',
value:[{id:1, data:4}, {id:2, data:5}, {id:3, data:6}]
},
{
name: 'ccc',
value:[{id:1, data:7}, {id:2, data:8}, {id:3, data:7}]
},
{
name: 'ddd',
value:[{id:1, data:2}, {id:2, data:1}, {id:3, data:1}]
}
]

我需要将它转换成这个数组 -

const finalArray = [
{
id: 1, aaa: 1, bbb: 4, ccc: 7, ddd: 2
},
{
id: 2, aaa: 2, bbb: 5, ccc: 8, ddd: 1
},
{
id: 3, aaa: 3, bbb: 6, ccc: 7, ddd: 1
}
]

我现在的解决方案是

initialArray.reduce((accum, arrayData) => {
arrayData.value.forEach(element => {
if (accum.some(el => el.id === element.id)) {
accum.find(el => el.id === element.id)[arrayData.name] = element.data;
} else {
accum.push({ id: element.id, [arrayData.name]: element.data });
}
});
return accum;
}, []);

有没有更好更优雅的方法来做到这一点?我试图通过减少遍历每个数组的次数并使用更少的代码和更高的可读性来实现这一点。如您所见,每次迭代期间的 some 和 find 都会增加迭代次数。有什么办法可以减少吗?

最佳答案

function tranform(array) {
const obj = {}

array.forEach(({name, value}) => (value || []).forEach(({id, data}) => obj[id] = { id, ...obj[id], [name]: data } ))

return Object.values(obj)
}

const initialArray = [
{
name: 'aaa',
value:[{id:1, data:1}, {id:2, data:2}, {id:3, data:3}]
},
{
name: 'bbb',
value:[{id:1, data:4}, {id:2, data:5}, {id:3, data:6}]
},
{
name: 'ccc',
value:[{id:1, data:7}, {id:2, data:8}, {id:3, data:7}]
},
{
name: 'ddd',
value:[{id:1, data:2}, {id:2, data:1}, {id:3, data:1}]
}
]

console.log(tranform(initialArray))

关于javascript - 将多维对象数组缩减为单个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55125693/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com