javascript | Object grouping

后端 未结 10 1283
不思量自难忘°
不思量自难忘° 2020-11-27 05:29

I have an object. It looks like below:

[
  {
    \"name\":\"Display\",
    \"group\":\"Technical detals\",
    \"id\":\"60\",
    \"value\":\"4\"
  },
  {
           


        
10条回答
  •  心在旅途
    2020-11-27 06:11

    A bit different way, so we have a plain list of objects, and want to group it per property, but includes all related

    const data = [{'group':'1', 'name':'name1'},
    {'group':'2', 'name':'name2'},
    {'group':'2', 'name':'name3'},
    ,{'group':'1', 'name':'name4'}]; 
    
    const groups = data .map( i => i.group);
    const uniqueGroups = Array.from(new Set(groups));
    const groupes = uniqueGroups.map( c => { 
                return  { group:c, names:[]};
            } ); 
    
    group.forEach( g => { 
                groupes.find( gg => gg.group === g.group).names.push(g.name);
    });
    

    so result would be like:

    [ {'group':'1', 'names':['name1', 'name4']},
    {'group':'2', 'names':['name2', 'name3']}
    

提交回复
热议问题