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