Group array of object nesting some of the keys with specific names

前端 未结 2 1992
北海茫月
北海茫月 2020-11-22 03:32

I have this array of objects, that I need to modify to make it easier the rendering.

const items = [
  {
    tab: \'Results\',
    section: \'2017\',
    ti         


        
2条回答
  •  梦谈多话
    2020-11-22 03:51

    This can be done with a clever combinartion of _.map and _.groupBy.

    const items = [
      {
        tab: 'Results',
        section: '2017',
        title: 'Full year Results',
        description: 'Something here',
      },
        {
        tab: 'Results',
        section: '2017',
        title: 'Half year Results',
        description: 'Something here',
      },
        {
        tab: 'Reports',
        section: 'Marketing',
        title: 'First Report',
        description: 'Something here',
      }
    ];
    
    function groupAndMap(items, itemKey, childKey, predic){
        return _.map(_.groupBy(items,itemKey), (obj,key) => ({
            [itemKey]: key,
            [childKey]: (predic && predic(obj)) || obj
        }));
    }
    
    var result = groupAndMap(items,"tab","sections", 
                       arr => groupAndMap(arr,"section", "items"));
    
    
    console.log(result);

提交回复
热议问题