I have an array of objects as follows. Each object has an array P2
inside it.
let input = [
{ "P2": [ 6, 6, 0 ] },
{ "P2": [ 3, 2, 0 ] },
{ "P2": [ 5, 1, 0 ] },
]
I want the desired result. as you can see, i am adding the elements and putting the result in the last element. for e.g. adding 6+6+0 and putting the result in last element as 12. Similarly for other objects inside the array. So the final output will look like this.
[
{ "P2": [ 6, 6, 0, 12 ] },
{ "P2": [ 3, 2, 0, 5 ] },
{ "P2": [ 5, 1, 0, 6 ] },
]
I am able to achieve this with a simple loop and reduce function as shown below.
input.forEach(arrayItem => {
let sum = arrayItem.P2.reduce((partialSum, a) => partialSum + a, 0);
arrayItem.P2.push(sum)
});
console.log(input)
Its fine till here. but it gets really interesting when i have dynamic input. for e.g. inside for static P2
values, i can have anything else. For e.g. shown below are the 2 examples of dynamic input.
let input = [
{ "P1": [ 6, 6, 0 ] },
{ "P2": [ 3, 2, 0 ] },
{ "P3": [ 5, 1, 0 ] },
]
OR
let input = [
{ "P2": [ 3, 3, 3, 2 ] },
{ "P2": [ 7, 7, 7, 4 ] },
{ "Total": [ 5, 1, 4, 6 ] },
]
Can someone let me know how to modify my code if there is dynamic property names like this.
p2 p3, total
Object.keys()
to get an array of property names, and then iterate through that however you want.input[input.length-1]
to get the last element andObject.keys(input[input.length-1])[0]
to get its key value.