如果其他对象中的键是相同的,则如何检入多个对象,然后对这些值求和。
例如,在这种情况下,我想要将A和B的所有值相加。
[{
"firstObject": 1,
"subObjects": [{
"A": 1,
"B": 2
}, {
"C": 3,
"D": 1
}]
}, {
"firstObject": 2,
"subObjects": [{
"A": 0,
"C": 5
}, {
"B": 2,
"D": 2
}]
}]
有什么想法吗?
答案 0 :(得分:0)
您可以使用reduce()
方法,然后返回对象作为结果。您还可以在结果let {A, B} = result
上使用对象解构来获取单独变量中的值。
const data = [{"firstObject":1,"subObjects":[{"A":1,"B":2},{"C":3,"D":1}]},{"firstObject":2,"subObjects":[{"A":0,"C":5},{"B":2,"D":2}]}];
const result = data.reduce((r, {subObjects}) => {
subObjects.forEach(({A, B}) => {
if(A) r.A = (r.A || 0) + A
if(B) r.B = (r.B || 0) + B
})
return r;
}, {})
console.log(result)

答案 1 :(得分:0)
您可以对array#reduce
对象中的每个键使用subObject
,对该值求和并将其添加到对象中。
const data = [{ "firstObject": 1, "subObjects": [{ "A": 1, "B": 2 }, { "C": 3, "D": 1 } ] }, { "firstObject": 2, "subObjects": [{ "A": 0, "C": 5 }, { "B": 2, "D": 2 } ] } ],
result = data.reduce((r,{subObjects}) => {
subObjects.forEach(o => {
Object.keys(o).forEach(k => {
r[k] = (r[k] || 0) + o[k];
});
});
return r;
},{});
console.log(result);

答案 2 :(得分:0)
使用函数reduce
对值进行求和的替代方案以及用于选择特定值的targets
数组,在这种情况下,只有[A, B]
var array = [{ "firstObject": 1, "subObjects": [{ "A": 1, "B": 2 }, { "C": 3, "D": 1 } ] }, { "firstObject": 2, "subObjects": [{ "A": 0, "C": 5 }, { "B": 2, "D": 2 } ] }],
targets = ['A', 'B'],
result = array.reduce((a, c) => {
targets.forEach(t => a[t] = c.subObjects.reduce((aa, ac) => aa + (ac[t] || 0), a[t] || 0));
return a;
}, {});
console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://codepen.io/egomezr/pen/dmLLwP.js"></script>
&#13;
答案 3 :(得分:0)
您可以使用reduce()
和spread syntax
来获取所需的结果。
<强>样本强>
const data = [{
"firstObject": 1,
"subObjects": [{
"A": 1,
"B": 2
}, {
"C": 3,
"D": 1
}]
}, {
"firstObject": 2,
"subObjects": [{
"A": 0,
"C": 5
}, {
"B": 2,
"D": 2
}]
}];
let result = data.reduce((r,{subObjects})=>[...r,...subObjects],[]).reduce((r,{A,B})=>{
r['A']+=+(A||0);
r['B']+= +(B||0);
return r;
},{A:0,B:0});
console.log(result)
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;