我有这个对象数组,我需要对其进行修改以使其更容易渲染。
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 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>
关于javascript - 嵌套一些具有特定名称的键的对象组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59463151/