JC *_*cia 4 javascript arrays grouping nested object
我有这个对象数组,我需要修改它以使渲染更容易。
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',
},
...
];
Run Code Online (Sandbox Code Playgroud)
我正在尝试修改它,按特定键对它们进行分组。这个想法是有这个输出。如您所见,键的名称可能与项目中的实际名称不同。我认为这与以前的帖子有点不同。
const output = [
{
tab: 'Results',
sections: [
{
section: '2017',
items: [ { 'item that belongs here' }, { ... } ],
},
},
{
tab: 'Reports',
sections: [
{
section: 'Marketing',
items: [ { ... }, { ... } ],
},
},
...
]
Run Code Online (Sandbox Code Playgroud)
我尝试使用lodash.groupby,但它并不完全符合我的要求。关于如何处理它的任何想法?
非常感谢!!
这可以用一个巧妙的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);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>Run Code Online (Sandbox Code Playgroud)