const group = (arr, key, childrenKey) =>
Object.values(arr.reduce((acc, { [childrenKey]: children, ...n }) => {
const item = acc[n[key]] = acc[n[key]] ?? n;
if (children) {
children = (item[childrenKey] ?? []).concat(children);
item[childrenKey] = group(children, key, childrenKey);
}
return acc;
}, {}));const grouped = group(products, 'name', 'childItems');