javascript - 对象中数组的求和值

标签 javascript arrays node.js object

我有一个对象:

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/

相关文章:

javascript - Html 和 JavaScript : How to return user input

javascript - 通过匹配两个值的差异从数组中过滤对象

javascript - 通过中间件检查多权限

node.js - 如何使用sequelize获取表格列表

node.js - 在 Node.js 中读取文件

javascript - NODE JS 取消请求

javascript - 为 C3.js 格式化 JSON

javascript - 如何计算对象数组中的数字

javascript - webpack 为什么要构建 global.js?

javascript - 以编程方式激活自定义 TinyMCE 按钮