How do I concatenate all objects in an array into one object and remove duplicate properties?

Hello everyone in the community!
How to merge all objects inside one array, considering that the properties of different objects can be repeated (they need to be removed from the new object). Property names are not known in advance.

My sample data:

[
    {
    "property_1": "value",
    "property_2": "value"
    },
    {
    "property_1": "value",
    "property_3": "value"
    },
    {
    "property_1": "value",
    "property_4": "value"
    }
]

I need to get the following:

[
    {
    "property_2": "value",
    "property_3": "value",
    "property_4": "value"
    }
]

You can use the Array.reduce prototype function.

More details here: Array.prototype.reduce() - JavaScript | MDN

Your example is missing property_1 so I’ll assume this one also has to persist.

Example code:

const myData = [
    {
    "property_1": "value",
    "property_2": "value"
    },
    {
    "property_1": "value",
    "property_3": "value"
    },
    {
    "property_1": "value",
    "property_4": "value"
    }
];

const consolidatedObject = myData.reduce((accumulator, currentItem) => {
    return {...accumulator, ...currentItem};
}, {});
console.log(consolidatedObject);
1 Like

@krynble, thanks for the help, but this code doesn’t work for me.
How do I need to adapt it and in what context of use would your presented code work?
I’m trying to figure out JS as tasks come in, but some things baffle me.
For example, you sent a sample code that does not work for me, what should I do next? It is very difficult to understand the context of a function node.

My workflow:

My target array:

Your code:


Ah, my code was an example of how this could be done.

The actual code should be something like this:

return [{json: items.reduce((accumulator, currentItem) => {
    return {...accumulator, ...currentItem.json};
}, {})}];

This should be all you need.

1 Like

@krynble, thank you! Work great!
I suffered for two days, tried to solve it myself). You did it in a few minutes. Thanks again!

1 Like

I’m glad it worked!

Keep automating :metal:

1 Like

Thanks to all your team! Your product gives a sense of limitless no-code possibilities!

2 Likes