Creating A Sum Of Nested Object Values In Javascript
I'm using the following code to query an API, which is working well to return nested values in JSON: const obj = response.data.map(function(item) { return [item.id, item.jobNumber
Solution 1:
You can do it using Array#map()
to create a new array and Array#reduce()
to sum the amountString
const apiJson = {"data":[{"id":100,"jobNumber":1,"jobTasks":[{"id":12,"cost":{"amountString":100}},{"id":13,"cost":{"amountString":500}}]},{"id":101,"jobNumber":2,"jobTasks":[{"id":14,"cost":{"amountString":100}},{"id":15,"cost":{"amountString":200}}]}]};
const output = apiJson.data.map(d=>({
jobNumber : d.jobNumber,
tasksCost : d.jobTasks.reduce((a,b)=>a.cost.amountString+b.cost.amountString)
}));
console.log(output);
Solution 2:
You can use reduce
method which accepts a callback
method.
Also, use forEach
method in order to iterate data
items.
var json={
"data": [
{
"id": 100,
"jobNumber": 1,
"jobTasks": [
{
"id": 12,
"cost": {
"amountString": 100
}
},
{
"id": 13,
"cost": {
"amountString": 500
}
}
]
},
{
"id": 101,
"jobNumber": 2,
"jobTasks": [
{
"id": 14,
"cost": {
"amountString": 100
}
},
{
"id": 15,
"cost": {
"amountString": 200
}
}
]
}]
}
json.data.forEach(function(item){
var sum=item.jobTasks.reduce(function(sum,elem){
return sum+elem.cost.amountString;
},0);
console.log('jobNumber'+item.jobNumber+' '+sum);
});
Solution 3:
first Update your json , "}" is missing from jobTasks of second object of array data :
"jobTasks":[{"id":14,"cost":{"amountString":100}},{"id":15,"cost":{"amountString":200}}]
Now To get Output:
i = 0,1
item.jobTasks[i]cost.amountString;
Solution 4:
Here is a solution using object-scan. We use it for most of our data processing now. It does take a moment to wrap your head around though as it is versatile.
// const objectScan = require('object-scan');constgetCounts = (data) => objectScan(['data[*].jobTasks[*].cost.amountString'], {
filterFn: ({ parents, value, context }) => {
const jobNumber = parents[3].jobNumber;
context[jobNumber] = (context[jobNumber] || 0) + value;
}
})(data, {});
const apiJson = { data: [{ id: 100, jobNumber: 1, jobTasks: [{ id: 12, cost: { amountString: 100 } }, { id: 13, cost: { amountString: 500 } }] }, { id: 101, jobNumber: 2, jobTasks: [{ id: 14, cost: { amountString: 100 } }, { id: 15, cost: { amountString: 200 } }] }] };
console.log(getCounts(apiJson));
// => { '1': 600, '2': 300 }
.as-console-wrapper {max-height: 100%!important; top: 0}
<scriptsrc="https://bundle.run/object-scan@13.8.0"></script>
Disclaimer: I'm the author of object-scan
Post a Comment for "Creating A Sum Of Nested Object Values In Javascript"