const arr1 = [
{
id: 1,
name: 'aa',
children: [
{
id: 2,
name: 'aa-a',
},
],
},
]
const arr2 = [
{
id: 1,
name: 'bb',
children: [
{
id: 2,
name: 'bb-a',
},
],
},
]
arr1.forEach((v) => {
arr2.forEach((s) => {
if (v.id === s.id) {
v.name = s.name
}
v.children &&
v.children.forEach((subV) => {
s.children &&
s.children.forEach((subS) => {
if (subV.id === subS.id) {
subV.name = subS.name
}
})
})
})
})
两个数组,两个数组层级都是两层,如果第一个数组中的对象的id和第二个数组的对象的id相同,则把第二个数组中对象的name赋值给第一个数组中对应的对象的name,现在是通过循环比对赋值的写法,有无更好的优化写法
我的话会这么写,因为树的结点id应该都不一样