Hi guys after doing various transformations I have this array of objects:
I need a dynamic function that allows me to create the following object, where data[i]
will be the sum of data[i]
values of the object above.
CodePudding user response:
because you use angular, you can transform your data response in a class/interface. Your entire json is a list of "Items"
export interface Item {
name: string,
data: number[]
}
// let rows: Item[] = your_json
then, you can create your totalItem as:
assuming all your data array have same length:
const rowValues = rows.map(x => x.data);
// using first row of your array, you can map results for each column of your matrix (rowValues is a matrix),
// then, iterating each row, you add the sum of specified column index
const values = rowValues[0].map((x, i) => {
let sum = 0;
rowValues.forEach(r => sum = r[i]);
return sum;
});
const totalObj = {
name: 'Total',
data: values
};
Is not the best solution, but I think is working
CodePudding user response:
Here is a solution for your problem within two looping structure
let rowData = [
{
"name": "TEST1",
"data": [
1,
2
]
},
{
"name": "TEST2",
"data": [
1,
2
]
},
{
"name": "TEST3",
"data": [
1,
2
]
}
]
var result = Array(rowData.length ? rowData[0].data.length : 0).fill(0)
rowData.map(ele=>ele.data?.map((e,idx)=>result[idx] =e || 0))
var output = {"name":"Total","data":result};
console.log(output)