我需要添加不同对象的相同元素并返回final volumn{ mono: color:}
。请参阅以下代码:
//function to add different objects
function addMonoColorVolumn(objects) {
var volumn = {
mono: [],
color: []
};
var mono = 0,
color = 0;
function addValusCB(obj) {
if (obj.monoTotal) {
mono += obj.monoTotal;
volumn.mono.push(mono);
}
if (obj.colorTotal) {
color += obj.colorTotal;
volumn.color.push(color);
}
}
if (objects.length) {
//if objects length is more then 0 than call the callback fn.
objects.forEach(addValusCB);
}
return volumn;
}
function main() {
var testObjects = [{
monoTotal: 100,
colorTotal: 200
}, {
monoTotal: 100,
colorTotal: 200
}, {
monoTotal: 100,
colorTotal: 200
}];
console.log(testObjects);
console.log(addMonoColorVolumn(testObjects)) //output should be object{color:1200,mono:600}
}
main();
我是javascript新手请指导我解决此问题。这是我的小提琴Running fiddel。
答案 0 :(得分:0)
您可以使用Array#reduce
并对所需的属性求和。
var testObjects = [{ monoTotal: 100, colorTotal: 200 }, { monoTotal: 100, colorTotal: 200 }, { monoTotal: 100, colorTotal: 200 }],
sum = testObjects.reduce(function (r, o) {
['mono', 'color'].forEach(function (k) {
r[k] = (r[k] || 0) + o[k + 'Total'];
});
return r;
}, {});
console.log(sum);
答案 1 :(得分:0)
或者,相反减少,您可以稍微修改您的代码,如下所示:
//function to add different objects
function addMonoColorVolumn(objects) {
var volumn = {
mono: 0,
color: 0
};
var mono = 0,
color = 0;
function addValusCB(obj) {
if (obj.monoTotal) {
mono += obj.monoTotal;
volumn.mono=mono;
}
if (obj.colorTotal) {
color += obj.colorTotal;
volumn.color=color;
}
}
if (objects.length) {
//if objects length is more then 0 than call the callback fn.
objects.forEach(addValusCB);
}
return volumn;
}
function test() {
var testObjects = [{
monoTotal: 100,
colorTotal: 200
}, {
monoTotal: 100,
colorTotal: 200
}, {
monoTotal: 100,
colorTotal: 200
}];
console.log(testObjects);
console.log(addMonoColorVolumn(testObjects)) //output should be object{color:1200,mono:600}
}
test();
//function to add different objects
function addMonoColorVolumn(objects) {
var volumn = {
mono: 0,
color: 0
};
var mono = 0,
color = 0;
function addValusCB(obj) {
if (obj.monoTotal) {
mono += obj.monoTotal;
volumn.mono=mono;
}
if (obj.colorTotal) {
color += obj.colorTotal;
volumn.color=color;
}
}
if (objects.length) {
//if objects length is more then 0 than call the callback fn.
objects.forEach(addValusCB);
}
return volumn;
}
function test() {
var testObjects = [{
monoTotal: 100,
colorTotal: 200
}, {
monoTotal: 100,
colorTotal: 200
}, {
monoTotal: 100,
colorTotal: 200
}];
// console.log(testObjects);
console.log(addMonoColorVolumn(testObjects)) //output should be object{color:1200,mono:600}
}
test();