0π
I hope it will help you to achieve your solution
var dataArr=[{
id:1,
name:'japan',
parent_category_id:1,
parent_category_name:'asia'
},{
id:2,
name:'england',
parent_category_id:2,
parent_category_name:'europa'
},{
id:3,
name:'korea',
parent_category_id:1,
parent_category_name:'asia'
},{
id:4,
name:'arab',
parent_category_id:1,
parent_category_name:'asia'
},{
id:5,
name:'south africa',
parent_category_id:3,
parent_category_name:'africa'
},{
id:6,
name:'spain',
parent_category_id:2,
parent_category_name:'europa'
},{
id:7,
name:'italy',
parent_category_id:2,
parent_category_name:'europa'
}],
output ={};
dataArr.map((item,index,arr)=>{
if(!output[item.parent_category_name]){
let result = arr.filter(val=>{
return val.parent_category_id==item.parent_category_id;
})
output[item.parent_category_name] = result.map(val=>{
return val.name;
});
}
});
console.log(output);
0π
Hereβs a function I use for grouping:
const groupBy = (arr, keyFn) => {
const grouped = arr.reduce( (grouping, item) => {
const key = keyFn(item);
grouping[key] = grouping[key] || [];
grouping[key].push(item);
return grouping;
}, {} );
return Object.keys(grouped)
.map(key => { return {key: key, group: grouped[key]}; });
}
You might call it like so:
const itemByCategoryName = (items) => {
const keyFn = item => item.parent_category_name
return groupBy(items, keyFn)
.map(group => { return { parent_category_name: group.key, grouped_items: group.group }; });
}
The output is an array of objects with key and nested array of items.
Source:stackexchange.com