将对象的组数组嵌套到具有特定名称的一些键

时间:2018-01-24 15:14:05

标签: javascript arrays object nested grouping

我有这个对象数组,我需要修改它以使渲染更容易。

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,但它并没有完全符合我的要求。 关于如何处理它的任何想法?

非常感谢!!

2 个答案:

答案 0 :(得分:3)

您可以使用没有其他库的对象。

该对象包含一个属性_,它保留给定嵌套组的嵌套数组。

var 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' }],
    keys = { tab: 'sections', section: 'items' }, // or more if required
    result = [],
    temp = { _: result };

items.forEach(function (object) {
    Object.keys(keys).reduce(function (level, key) {
        if (!level[object[key]]) {
            level[object[key]] = { _: [] };
            level._.push({ [key]: object[key], [keys[key]]: level[object[key]]._ });
        }
        return level[object[key]];
    }, temp)._.push({ title: object.title, description: object.description });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

这可以通过_.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>
&#13;
&#13;
&#13;