I am working on a project where CouchDB returns JSON in this structure.
[{"Key":"dep_012345_1","Record":
{"AccNo":"012345","Amount":"50000","BusinessId":"1","DataType":"deposit","ID":"dep_012345_1","Invested":"no","ProfitReturned":"no","Share":"75"}
},
{"Key":"dep_123456_1","Record":
{"AccNo":"123456","Amount":"60000","BusinessId":"1","DataType":"deposit","ID":"dep_123456_1","Invested":"no","ProfitReturned":"no","Share":"80"}
}]
Here How can I iterate? basically, I want to add the amounts by iterating.
>Solution :
You can use the reduce function:
const data = [{
"Key": "dep_012345_1", "Record":
{ "AccNo": "012345", "Amount": "50000", "BusinessId": "1", "DataType": "deposit", "ID": "dep_012345_1", "Invested": "no", "ProfitReturned": "no", "Share": "75" }
},
{
"Key": "dep_123456_1", "Record":
{ "AccNo": "123456", "Amount": "60000", "BusinessId": "1", "DataType": "deposit", "ID": "dep_123456_1", "Invested": "no", "ProfitReturned": "no", "Share": "80" }
}];
const sum = data.reduce((prev, current) => prev + parseInt(current.Record.Amount, 10), 0);
console.log(sum); // prints 110000