[英]Summing values of JSON objects in javascript
我有一个返回数据的 API,例如:
{
"attributes": {
"type": "Opportunity"
},
"Amount": 175.36,
"Owner": {
"attributes": {
"type": "User"
},
"Name": "Steve Knight"
}
},
{
"attributes": {
"type": "Opportunity"
},
"Amount": 6800,
"Owner": {
"attributes": {
"type": "User"
},
"Name": "Bob Smith"
}
}
etc...
这些代表机会,因此每个销售人员都会有多个。 我正在尝试返回一个对象,该对象对每个销售人员的金额求和并返回如下内容:
{Steve Knight: 5590, Bob Smith: 98722, John Jones: 12347893}
我尝试按所有者名称对对象进行分组,但是我不确定如何对金额求和
var groupBy = require('lodash.groupby');
var grouped = groupBy(data, function(x) {
return x.Owner.Name;
});
最好使用Array.prototype
的reduce
方法
console.clear(); (function() { "use strict"; function reduce(coll, elem, idx, arr) { coll[elem.Owner.Name] = coll[elem.Owner.Name] || 0; coll[elem.Owner.Name] += elem.Amount return coll; } const data = [ { attributes: { type: "Opportunity" }, Amount: 175.36, Owner: { attributes: { type: "User" }, Name: "Steve Knight" } }, { attributes: { type: "Opportunity" }, Amount: 100.16, Owner: { attributes: { type: "User" }, Name: "John Doe" } }, { attributes: { type: "Opportunity" }, Amount: 6.00, Owner: { attributes: { type: "User" }, Name: "John Doe" } }, { attributes: { type: "Opportunity" }, Amount: 101.65, Owner: { attributes: { type: "User" }, Name: "Steve Knight" } }, { attributes: { type: "Opportunity" }, Amount: 6800, Owner: { attributes: { type: "User" }, Name: "Bob Smith" } } ]; const reducedData = data.reduce(reduce, {}) console.log(reducedData) }());
如果键名存在,则将已经存在的值累加到新的值中,否则只需添加初始值和名称
const arr = [{ "attributes": { "type": "Opportunity" }, "Amount": 175.36, "Owner": { "attributes": { "type": "User" }, "Name": "Steve Knight" } }, { "attributes": { "type": "Opportunity" }, "Amount": 100, "Owner": { "attributes": { "type": "User" }, "Name": "Steve Knight" } }, { "attributes": { "type": "Opportunity" }, "Amount": 6800, "Owner": { "attributes": { "type": "User" }, "Name": "Bob Smith" } } ] const result = arr.reduce((acc, x) => { const key = x.Owner.Name; const amount = x['Amount']; if (!acc[key]) { acc[key] = amount; } else { acc[key] = acc[key] + amount; } return acc; }, {}); console.log(result)
你可以在下面试试这个:
let output = {}
data.map(function (item) {
if (output.hasOwnProperty(item.Owner.Name)) {
output[item.Owner.Name] = item.Amount;
} else {
output[item.Owner.Name] += item.Amount;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.