Using plain JavaScript or lodash, what’s the easiest way to transform an array of objects into a single object, while concatenating any array values?
I can achieve it on a single property using _.flatMap(before, "nodes")
but not sure how to include all properties.
For example:
const before = [
{
nodes: [
{ "id": "1" },
{ "id": "2" }
],
links: [
{ "source": "1", "target": "2" }
],
},
{
nodes: [
{ "id": "3" },
{ "id": "4" },
{ "id": "5" },
{ "id": "6" }
],
links: [
{ "source": "3", "target": "4" },
{ "source": "5", "target": "6" }
],
}
];
const after = {
nodes: [
{ "id": "1" },
{ "id": "2" },
{ "id": "3" },
{ "id": "4" },
{ "id": "5" },
{ "id": "6" }
],
links: [
{ "source": "1", "target": "2" },
{ "source": "3", "target": "4" },
{ "source": "5", "target": "6" }
],
};
5
Answers
You can achieve this using vanilla js using
reduce
andObject.entries
as:Since you want to merge array into one, you should use
reduce
instead ofmap
. Following should workreduce
will work with each element in iterative manner from left to right.Hope this helps
One possible solution using lodash:
The result is a new object that contains these combined arrays.
Following below code:
You can use
Array.reduce()
to achieve this efficiently.Please find the following code: