如何按指定键分组对象数组并调整结构以简化渲染?
实现嵌套分组的两种方案
我明白你想要的是两层嵌套的分组结构——先按tab归类,每个tab下再按section聚合对应的条目。Lodash的groupBy确实只能完成单层分组,所以得配合其他方法来实现你要的嵌套结构,下面给你两种可行的方案:
方案一:使用Lodash链式调用实现
通过_.chain把多层分组和结构转换串联起来,代码更简洁:
const _ = require('lodash'); 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 = _.chain(items) // 第一步:按tab做第一层分组 .groupBy('tab') // 第二步:把每个tab的分组转换成目标结构 .map((groupedItems, tabName) => ({ tab: tabName, // 第三步:对当前tab下的条目按section做第二层分组,并转换sections结构 sections: _.chain(groupedItems) .groupBy('section') .map((itemsInSection, sectionName) => ({ section: sectionName, items: itemsInSection // 若需剔除tab/section字段,可写成 _.map(itemsInSection, item => _.omit(item, ['tab', 'section'])) })) .value() })) // 把分组后的对象转为数组 .value(); console.log(output);
这段代码的逻辑是:先按tab把所有条目分成大组,再对每个大组内的条目按section细分,最后把每层的键值对结构转换成你需要的对象格式。
方案二:原生JavaScript实现(无需依赖库)
如果不想引入Lodash,可以用原生JS的对象和数组方法手动构建结构:
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 tempMap = {}; items.forEach(item => { const { tab, section, ...itemContent } = item; // 如果当前tab未初始化,创建基础结构 if (!tempMap[tab]) { tempMap[tab] = { tab, sections: [] }; } // 检查当前tab下是否已有该section const targetSection = tempMap[tab].sections.find(s => s.section === section); if (targetSection) { // 已有section,直接添加条目 targetSection.items.push(itemContent); } else { // 无对应section,创建新的section并加入数组 tempMap[tab].sections.push({ section, items: [itemContent] }); } }); // 把临时对象的值转为数组,得到最终结构 const output = Object.values(tempMap); console.log(output);
这里用forEach遍历每个条目,通过临时对象tempMap跟踪每个tab和section的存在状态,逐步构建嵌套结构。如果需要保留条目中的tab和section字段,把itemContent换成item即可。
内容的提问来源于stack exchange,提问作者JC Garcia
相关产品推荐
相关产品推荐

