I need to merge a nested array based on the values from a parent key.
What is the error message (if any)?
Please share your workflow
Data - receive the data in this format, where the ref is duplicated across multiple items, each with a nested object. I need a single instance:
[
{
"ref": "00075925",
"Items": [
{
"ID": 1
}
]
},
{
"ref": "00075925",
"Items": [
{
"ID": 2
}
]
},
{
"ref": "00075925",
"Items": [
{
"ID": 3
}
]
},
{
"ref": "00075926",
"Items": [
{
"ID": 1
}
]
},
{
"ref": "00075926",
"Items": [
{
"ID": 2
}
]
},
{
"ref": "00075926",
"Items": [
{
"ID": 3
}
]
}
]
Output should be:
[
{
"ref": "00075925",
"Items": [
{
"ID": 1
},
{
"ID": 2
},
{
"ID": 3
}
]
},
{
"ref": "00075926",
"Items": [
{
"ID": 1
},
{
"ID": 2
},
{
"ID": 3
}
]
}
]
Share the output returned by the last node
I need the output to look like the example above, where the items are merged on the ref, and the nested object array is built from the input, but for the life of me I can’t get the json right.
Hi @Quiss Welcome!
Summarize groups on a field the way a pivot table does, and its Append aggregation collects another field across each group.
Summarize: set Fields to Split By to ref, add one aggregation of Append on field Items, and set Output Format to “Each Split in a Separate Item”.
Edit Fields: add ref as a String set to {{ $json.ref }}, and Items as an Array set to {{ $json.appended_Items.reduce((all, one) => all.concat(one), []) }}.
Append names its output appended_Items and keeps each source array whole, so the reduce concatenates them back into one Items array. Summarize | Nodes | n8n Docs
The easiest way I’d handle this in n8n is with a Code node. Since the ref is the value you want to group by, you can loop through the incoming items and collect all the nested Items under the same ref. const grouped = {};
for (const item of $input.all()) {
const { ref, Items = } = item.json;
if (!grouped[ref]) {
grouped[ref] = {
ref,
Items:
};
}