Ich habe eine API, die Daten wie diese zurückgibt:
{
"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...
Diese stellen Chancen dar und so hat jeder Verkäufer mehrere. Ich versuche, ein Objekt zurückzugeben, das die Beträge für jeden Verkäufer summiert und Folgendes zurückgibt:
{Steve Knight: 5590, Bob Smith: 98722, John Jones: 12347893}
Ich habe versucht, die Objekte nach Eigentümernamen zu gruppieren, bin mir jedoch nicht sicher, wie ich die Beträge summieren soll
var groupBy = require('lodash.groupby');
var grouped = groupBy(data, function(x) {
return x.Owner.Name;
});
Verwenden Sie am besten die reduce
Methode vonArray.prototype
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)
}());
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen