我有两个对象数组。一个数组包含项目列表,另一个数组包含类别列表。我想创建一个基于categoryIds的新数组。我尝试使用lodash。但是,无法得到正确的解决方案。合并与第二组对象的Javascript数组和组
我可以使用循环来做到这一点。但是,我正在寻找更干净的方法。
var items = [
{
id: '001',
name: 'item1',
description: 'description of item1',
categoryId: 'cat1'
},
{
id: '002',
name: 'item2',
description: 'description of item2',
categoryId: 'cat2'
},
{
id: '003',
name: 'item3',
description: 'description of item3',
categoryId: 'cat1'
},
{
id: '004',
name: 'item4',
description: 'description of item4'
}
];
var categories = [
{
id: 'cat1',
name: 'Category1'
},
{
id: 'cat2',
name: 'Category2'
}
];
预计输出
[
{
categoryId: 'cat1',
name: 'Category1',
items: [
{
id: '001',
name: 'item1',
description: 'description of item1',
categoryId: 'cat1'
},
{
id: '003',
name: 'item3',
description: 'description of item3',
categoryId: 'cat1'
}
]
},
{
categoryId: 'cat2',
name: 'Category2',
items: [
{
id: '002',
name: 'item2',
description: 'description of item2',
categoryId: 'cat2'
}
]
},
{
categoryId: '',
name: '',
items: [
{
id: '004',
name: 'item4',
description: 'description of item4'
}
]
}
]
https://jsfiddle.net/sfpd3ppn/
感谢您的帮助
* - 哪里是你的企图:“我可以用循环做到这一点。”?你的小提琴只包括输入对象和所需的输出。 – nnnnnn
对不起。我已经更新了jsfiddle。请看一看。 https://jsfiddle.net/sfpd3ppn/1/ – jintoppy