嗨,我有以下JSON对象;
var obj1 = {"a":1,"b":1,"c":1};
var obj2 = {"a":2,"b":2,"c":2};
var obj3 = {"a":3,"b":3,"c":3};
我想相加或减去3个json对象 我希望最终结果为
{"a":6,"b":6,"c":6}
我知道使用不同类型的循环非常简单。但是我想知道javascript中是否存在任何功能来合并多个JSON对象并添加或减去每个属性(无循环)。
在数组中是否有像reduce
这样的函数:
如下所示:
var squares = arr.concat(arr2).reduce((t,n)=>t+n);
谢谢
答案 0 :(得分:3)
没有这样的内置函数可以自动完成类似的任务,但是编写自己的代码来实现所需功能很简单:
var obj1 = {"a":1,"b":1,'c':1};
var obj2 = {"a":2,"b":2,'c':2};
var obj3 = {"a":3,"b":3,'c':3};
const combined = [obj1, obj2, obj3].reduce((a, obj) => {
Object.entries(obj).forEach(([key, val]) => {
a[key] = (a[key] || 0) + val;
});
return a;
});
console.log(combined);
答案 1 :(得分:3)
您可以仅遍历object
个属性之一并构造结果:
let res = {};
for (p in obj1) {
res[p] = obj1[p] + (obj2[p] || 0) + (obj3[p] || 0);
}
演示:
var obj1 = {"a":1,"b":1,"c":1};
var obj2 = {"a":2,"b":2,"c":2};
var obj3 = {"a":3,"b":3,"c":3};
let res = {};
for (p in obj1) {
res[p] = obj1[p] + (obj2[p] || 0) + (obj3[p] || 0);
}
console.log(res);