Javascript 用特定名称嵌套某些键的对象的组数组

Javascript 用特定名称嵌套某些键的对象的组数组,javascript,arrays,object,nested,grouping,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

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

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
,但它并不完全符合我的要求。 你知道怎么做吗


非常感谢

这可以通过巧妙地组合
.map
.groupBy
来实现

const项=[
{
选项卡:“结果”,
章节:“2017年”,
标题:“全年业绩”,
描述:'这里有东西',
},
{
选项卡:“结果”,
章节:“2017年”,
标题:“半年业绩”,
描述:'这里有东西',
},
{
选项卡:“报告”,
“营销”部分,
标题:"第一次报告",,
描述:'这里有东西',
}
];
功能组和映射(项、项键、子键、predic){
return u.map(u.groupBy(items,itemKey),(obj,key)=>({
[itemKey]:键,
[childKey]:(predic和predic(obj))| | obj
}));
}
var result=groupAndMap(项目、“选项卡”、“部分”,
arr=>groupAndMap(arr,“部分”、“项目”);
控制台日志(结果)

您可以使用一个对象,而无需额外的库

该对象包含一个属性<代码>\
,该属性保留给定嵌套组的嵌套数组

var items=[{tab:'Results',section:'2017',title:'Full year Results',description:'somethine here'},{tab:'Results',section:'2017',description:'somethine here'},{tab:'Reports',section:'Marketing',title:'First Report',description:'somethine here,
键={tab:'sections',section:'items'},//或更多(如果需要)
结果=[],
temp={{结果};
items.forEach(函数(对象){
对象。键(键)。减少(功能(级别,键){
如果(!级别[对象[键]]){
级别[对象[键]]={{}:[]};
level.u.push({[key]:对象[key],[keys[key]]:level[object[key]].});
}
返回级别[对象[键];
}.push({title:object.title,description:object.description});
});
控制台日志(结果)

。作为控制台包装{max height:100%!important;top:0;}
您希望分组哪个键?解决方案的可能副本看起来非常整洁,谢谢!另外,@Jamiec解决方案工作得很完美,现在唯一的疑问是哪一个更有效…@JCGarcia我敢打赌这一个,比使用lodash更自然@尼娜,
地图
比使用简单对象
{}好吗?非常好的解决方案顺便说一句@sjahan,使用for循环的对象可能更快。我个人总是会听从Nina的更好的知识;)但这不会在上进行第二级聚合sections@Jamiec,抱歉,尚未看到嵌套的分组。