我有兩個對象數組。一個數組包含項目列表,另一個數組包含類別列表。我想創建一個基於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