[英]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.