我有一个对象:
var stuffData = {
'Fruit': [{
'Name': 'Apple',
'Price': '2'
}, {
'Name': 'Kiwi',
'Price': '4'
}],
'Sport': [{
'Name': 'Ball',
'Price': '10'
}, {
'Name': 'Bike',
'Price': '120'
}],
'Kitchen': [{
'Name': 'Knife',
'Price': '8'
}, {
'Name': 'Fork',
'Price': '7'
}]
}
现在我想从价格列中获取总和。
我想过这个
for (var key in stuffData)
{
// and for each key i have to add new array with sum of price or what?
// But how will I display this sum then?
// I haven't any idea how can I deal with this
}
最佳答案
这样的事情应该可以工作,映射对象,并减少每个对象的总和
var stuffData = {
'Fruit': [{
'Name': 'Apple',
'Price': '2'
}, {
'Name': 'Kiwi',
'Price': '4'
}],
'Sport': [{
'Name': 'Ball',
'Price': '10'
}, {
'Name': 'Bike',
'Price': '120'
}],
'Kitchen': [{
'Name': 'Knife',
'Price': '8'
}, {
'Name': 'Fork',
'Price': '7'
}]
}
var o = {};
Object.keys(stuffData).forEach(function(key) {
o[key] = stuffData[key].map(function(item) {
return parseInt(item.Price, 10);
}).reduce(function(a,b) {
return a + b;
});
});
document.body.innerHTML = '<pre>' + JSON.stringify(o, 0, 4) + '</pre>';
结果是
{
Fruit: 6,
Sport: 130,
Kitchen: 15
}
关于javascript - 对象中数组的求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36847330/