一尘不染

对象的组数组,嵌套具有特定名称的某些键

javascript

我有此对象数组,需要对其进行修改以使其更容易呈现。

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',
  },
  ...
];

我正在尝试对其进行修改,并按特定的键将它们分组。这个想法是要有这个输出。如您所见,键的名称可能与项目中的实际名称不同。我认为这与以前的帖子有些不同。

const output = [
  {
    tab: 'Results',
    sections: [
      {
         section: '2017',
         items: [ { 'item that belongs here' }, { ... } ],
      },
  },
  {
    tab: 'Reports',
    sections: [
      {
         section: 'Marketing',
         items: [ { ... }, { ... } ],
      },
  },
...
]

我尝试使用lodash.groupby,但它并不能完全满足我的需求。关于如何处理它的任何想法?

非常感谢!!


阅读 256

收藏
2020-04-25

共1个答案

一尘不染

这可以用一个巧妙的combinartion完成_.map_.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);


<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
2020-04-25