Recently, I encountered a JavaScript object that was generated by a particular API. The object is structured in a way that it can potentially have multiple instances of the same 'equity' (such as Hitachi Home in this case):
{
"results": {
"holdings": [{
"equity": {
"text": "Hitachi Home"
},
"holding_pc": "6.48",
"sector": "Consumer Durables",
"shares_no": "1537.00",
"value_cr": "0.24"
}, {
"equity": {
"text": "Mahindra CIE"
},
"holding_pc": "6.34",
"sector": "Manufacturing",
"shares_no": "10376.00",
"value_cr": "0.24"
}, {
"equity": {
"text": "Schneider Infra"
},
"holding_pc": "5.33",
"sector": "Utilities",
"shares_no": "9518.00",
"value_cr": "0.20",
}, {
"equity": {
"text": "Hitachi Home"
},
"holding_pc": "2.18",
"sector": "Consumer Durables",
"shares_no": "437.00",
"value_cr": "0.12"
}]
}
}
I am currently exploring the best approach to develop a JavaScript function that can take this entire object as input, iterate through all the records, and consolidate the data so that records with the same 'equity' are summed and merged. For example, the equity 'Hitachi Home' should be consolidated as follows:
{
"results": {
"holdings": [{
"equity": {
"text": "Hitachi Home"
},
"holding_pc": "8.66",
"sector": "Consumer Durables",
"shares_no": "1974.00",
"value_cr": "0.36"
}, {
"equity": {
"text": "Mahindra CIE"
},
"holding_pc": "6.34",
"sector": "Manufacturing",
"shares_no": "10376.00",
"value_cr": "0.24"
}, {
"equity": {
"text": "Schneider Infra"
},
"holding_pc": "5.33",
"sector": "Utilities",
"shares_no": "9518.00",
"value_cr": "0.20",
}]
}
}
My objective is to create a JS function that can aggregate all equities with the same text. Below is a high-level overview of the function I am working on:
function transform(data) {
function sumHoldings(row) {
newrow = {};
newrow.equity = row.equity.text;
newrow.holding_pc = row.holding_pc;
return newrow;
}
for(var holdings in data.results) {
data.results.total_holdings = data.results.holdings.map(sumHoldings);
};
return data;
}