I have an array of objects that looks like the next example:
let tryout = [
{text: 1, video: 1, photo: 2, song: 1},
{text: 2, video: 3, photo: 1},
{text: 4, video: 2, photo: 2},
]
And I want to add them to get this kind of object at the end:
let newObjet = {
text: 7,
video: 6,
photo: 5,
song: 1
}
What would be the best way to do this. I am trying with reduce() but all I am getting is a merging of objects keys, and the values are not adding up.
One important thing is that I don't know what keys are gonna be inside of objects.
This is my attempt (not working as expected):
var resultObject = tryout.reduce(function(result, currentObject)
{
for (var key in currentObject)
{
if (currentObject.hasOwnProperty(key)) {
result[key] = currentObject[key];
}
}
return result;
}, {});
reduceis one way to achieve that.