请问这个小算法题怎么解决,花了1天多,不知道怎么处理

请问这个小算法题怎么解决,花了1天多,不知道怎么处理

let a = [

{

"parentId": "1",

"categoryId": [

"136",

"27"

]

},

{

"parentId": "14",

"categoryId": [

"1560",

"1598"

]

}

]

let b = [

{

"categoryName": "女装男装",

"categoryId": "1"

},

{

"categoryName": "生活服务",

"categoryId": "14"

}

]

上面有a 和 b 两个数组对象,我想根据a里面的parentId 和 b里面categoryId 取同一个 去重后,组合成如下的数组对象:

[

{

"parentId": "14",

"categoryName": "女装男装",

"categoryId": [

"136",

"27"

]

},

{

"parentId": "1",

"categoryName": "生活服务",

"categoryId": [

"1560",

"1598"

]

}

]

请问该怎么写


回答:

a.map(v => ({...v, categoryName: b.find(o => o.categoryId == v.parentId).categoryName}))
这里假设了必有对应id,如果存在无的情况需要处理下,find未找到会返回null


回答:

const bMap = {};

b.forEach(el=>{

bMap[el.id] = el

})

const last = a.map(el=>{

return {...el,categoryName:bMap[el.parentId]?.categoryName||''}

})

以上是 请问这个小算法题怎么解决,花了1天多,不知道怎么处理 的全部内容, 来源链接: utcz.com/p/936438.html

回到顶部