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.
4
Answers
you can iterate over each object in the array and dynamically access the property name using Object.keys() or Object.entries().
Using your second example
Just iterate and push a sum as the last element to the sub arrays:
You may also use the array map method as follows:
Now for this, you can use the array map method and
Object.keys()
andObject.values()
:And similarly for this one:
Or, if you choose to use
Object.entries()
andObject.fromEntries
:The problem with your code is that you are using
arrayItem.P2
in the function and expecting it to access every object inside the array. It will only work for ‘P2’ and won’t work for any other keys like ‘P1’, ‘P3’ and like that. So you need to access the array without explicitly mentioning thekey
names. For this you can useObject.keys
method. In your case you should be usingObject.keys(arrayItem)
to access the array inside the objects.