gpt4 book ai didi

javascript - 合并两个 Javascript 对象,其中每个键包含多个值

转载 作者:行者123 更新时间:2023-11-30 13:53:13 25 4
gpt4 key购买 nike

我目前正在学习 JavaScript,并且有一个关于我正在从事的项目的快速问题。目前,如果我想合并几个对象,如果键匹配则将值加在一起,或者如果键不存在则附加父对象,我可以执行以下操作:

var test1 = {
a: 12,
b: 8,
c: 17
};

var test2 = {
a: 22,
b: 8,
c: 9
};

var test3 = {
a: 33,
b: 23,
c: 1,
d: 2,
e: 9
};

function sumObjectsByKey(...objs) {
return objs.reduce((a, b) => {
for (let k in b) {
if (b.hasOwnProperty(k))
a[k] = (a[k] || 0) + b[k]
}
return a;
}, {});
console.log("endresult" + " " + sumObjectsByKey(test1, test2, test3));

当只有一个值时,这似乎工作得很好。例如:一个:22

所以这就是我的问题所在。如果对象看起来像这样怎么办:

var test1 = {
testSystem: {crit: "1", high: "0", med: "1", low: "22"}
testSystem1: {crit: "1", high: "0", med: "1", low: "22"}
testSystem2: {crit: "1", high: "0", med: "1", low: "22"}
testSystem3: {crit: "1", high: "0", med: "1", low: "22"}
};

var test2 = {
testSystem: {crit: "19", high: "305", med: "21", low: "212"}
4testSystem1: {crit: "111", high: "10", med: "31", low: "62"}
testSystem2: {crit: "21", high: "3", med: "11", low: "232"}
testSystem4: {crit: "13", high: "40", med: "15", low: "22"}
testSystem7: {crit: "21", high: "3", med: "112", low: "32"}
};

var test3 = {
testSystem5: {crit: "1", high: "0", med: "122", low: "122"}
testSystem2: {crit: "2", high: "6", med: "1", low: "222"}
testSystem3: {crit: "6", high: "0", med: "12", low: "212"}
testSystem4: {crit: "4", high: "8", med: "11", low: "2"}
};

我怎样才能修改上面的代码来遍历以执行与上面相同的操作?任何解释或帮助将不胜感激。谢谢。

最佳答案

您可以检查第二个对象是否有嵌套对象,然后调用嵌套对象的函数。

function sum(a, b) {
Object.keys(b).forEach(k => {
if (b[k] && typeof b[k] === 'object') return sum(a[k] = a[k] || {}, b[k]);
a[k] = (+a[k] || 0) + +b[k];
});
return a;
}

var test1 = { testSystem: { crit: "1", high: "0", med: "1", low: "22" }, testSystem1: { crit: "1", high: "0", med: "1", low: "22" }, testSystem2: { crit: "1", high: "0", med: "1", low: "22" }, testSystem3: { crit: "1", high: "0", med: "1", low: "22" } },
test2 = { testSystem: { crit: "19", high: "305", med: "21", low: "212" }, testSystem1: { crit: "111", high: "10", med: "31", low: "62" }, testSystem2: { crit: "21", high: "3", med: "11", low: "232" }, testSystem4: { crit: "13", high: "40", med: "15", low: "22" }, testSystem7: { crit: "21", high: "3", med: "112", low: "32" } },
test3 = { testSystem5: { crit: "1", high: "0", med: "122", low: "122" }, testSystem2: { crit: "2", high: "6", med: "1", low: "222" }, testSystem3: { crit: "6", high: "0", med: "12", low: "212" }, testSystem4: { crit: "4", high: "8", med: "11", low: "2" } };

console.log([test1, test2, test3].reduce(sum));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 合并两个 Javascript 对象,其中每个键包含多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57799881/

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