【发布时间】:2019-12-06 01:12:12
【问题描述】:
我需要合并两个数组:类别和产品。每个产品都有一个类别对象。我需要按类别组织,包括类别对象并保留空类别。 GroupBy 函数只包含一个参数。
const Categories= [
{id: 1, 'name': 'category1'}
{id: 2, 'name': 'category2'},
{id: 3, 'name': 'category3'},
{id: 4, 'name': 'category4'},
]
const Products= [
{id: 1, 'name': 'product1', category: {id: 1, name: 'category1'}},
{id: 2, 'name': 'product2', category: {id: 1, name: 'category1'}},
{id: 3, 'name': 'product3', category: {id: 2, name: 'category2'}},
{id: 4, 'name': 'product4', category: {id: 2, name: 'category2'}},
]
预期结果
const result = [
{
category: {id: 1, name: 'category1'},
products:[{id:1, name: 'produt1'}, {id: 2, name: 'produto1'} ]
},
{
category: {id: 2, name: 'category2'},
products:[{id:3, name: 'produt3'}, {id: 4, name: 'produto4'} ]
},
{
category: {id: 3, name: 'category3'},
products:[]
},
{
category: {id: 4, name: 'category4'},
products:[]
},
]
尝试:
for (i = 0; i < categoriesJson.length; i++) {
categoriesJson[i] = _.assign({}, categoriesJson[i], { products: [] })
for (j = 0; j < productsJson.length; j++) {
if(productsJson[j].categoryId.objectId === categoriesJson[i].objectId){
categoriesJson[i].products.push(productsJson[j])
}
}
}
【问题讨论】:
-
你到目前为止的努力?
-
如果您的问题得到解答,请点击左侧的灰色复选标记accept one of the answers。 Use lodash groupBy function to categorize objects in an array
-
@trincot 这是一个稍微不同的问题。如果
Products没有类别,OP 想在输出中添加一个空的products项目。但是,“太宽泛”我猜没有尝试 -
我明白了。是的,反正太宽泛了。 “没有代码,没有答案”(让我想到“没有痛苦,没有收获”)。如果添加尝试,我将撤消我的近距离投票。
-
我尝试了很多东西,你不知道。对于循环,从lodash分组,减少数组,我被这个问题困扰了好几天。 stackoverflow.com/questions/50840745/… 这个问题解决了我的问题,但给了我另一个问题:如何处理空类别。我将尝试编辑问题。抱歉,我是 lodash 和 stack 的新手。
标签: javascript arrays merge lodash