取一个包含多个对象的对象。这些对象可以有一个名为number
的特定键,其值为数字。
如何添加具有此键number
...
var myObject = {
item1 = {
name: "someName",
color: "someColor2",
number: intValue
},
item2 = {
name: "someName2",
color: "someColor2"
},
item3 = {
name: "someName3",
color: "someColor3",
number: intValue
},
item4 = {
name: "someName4",
color: "someColor4"
},
};
答案 0 :(得分:0)
var sum = 0;
for (var prop in myObject)
{
sum += myObject[prop].number || 0;
}
可能是某事的开头 ....
答案 1 :(得分:0)
这是Array.reduce
的完美用例!但是,由于您的输入是对象而不是数组,我们需要使用Object.keys
来获取项目名称列表,然后该列表将驱动reducer循环。
// your object def wasn't valid, so I made my own
var myObject = {
item1: { name: 'item one', color: 'red', number: 1 },
item2: { name: 'item two', color: 'orange', number: 2 },
item3: { name: 'item three', color: 'yellow', number: 3 },
item4: { name: 'item four', color: 'green', number: 4 },
item5: { name: 'item five', color: 'blue', number: 5 },
item6: { name: 'item six', color: 'indigo', number: 6 },
item7: { name: 'item seven', color: 'violet', number: 7 }
};
var total = Object.keys(myObject) //=> ['item1', 'item2', 'item3', 'item4', ...]
.reduce(function(sum, itemName) {
return sum += myObject[itemName].number;
}, 0);