JS:对具有多个属性的对象数组进行扁平化和精简,并组合值



我在这方面已经有一段时间了,但我不确定如何将下面的示例数据扁平化并减少为唯一的键值对,如果同一个键有多个,则该值将被组合。

示例:

const data = [
{ test: 200 },
{ test2: 300, test3: 100 },
{ test3: 400, test4: 150, test2: 50 },
];

预期结果:

const result = [
{ test: 200 }, 
{ test2: 350 }, 
{ test3: 500 }, 
{ test4: 150 }
];

有什么想法吗?

TIA-

试试这个:

const data = [
{ test: 200 },
{ test2: 300, test3: 100 },
{ test3: 400, test4: 150, test2: 50 }
];
const flattenedAndReduced = data.reduce((prev, current) => {
Object.keys(prev).forEach((key, index) => {
if (current[key]) {
prev[key] += current[key];
delete current[key];
}
});
Object.keys(current).forEach((key) => {
if (!prev[key]) prev[key] = current[key];
});
return { ...prev };
});
const flattenedAndReducedToArray = Object.keys(flattenedAndReduced).map((key) => ({
[key]: flattenedAndReduced[key]
}));

最新更新