In the process of sorting and grouping data by the first word separated by an underscore (_), the expected result is to have 3 groups (e.g. orders, items and ""
). Is there a way to assign a specific value (e.g. Others) to the empty string group? Check out this StackBlitz link for reference.
let rawData = [
{ name : 'orders_list', id : 10},
{ name : 'orders_price', id : 7},
{ name : 'items_list', id : 12 },
{ name : 'items_price', id : 7},
{ name : 'others-list', id : 7},
{ name : 'secondOthers-list', id : 7},
]
let data = rawData.reduce((r, e) => {
let group = e.name.substr(0, e.name.indexOf('_'));
if(!r[group]) {
r[group] = {group, children: [e]}
} else {
r[group].children.push(e);
}
return r;
}, {})
let result = Object.values(data)
console.log(result)