来自思否的一个问答。
原文链接
正文
问题
提问者大概需求为将下面的两个数组,经过处理后变为预期的数组
原数组
javascript">const arr1 = [{ uid: 2 }, { uid: 3 }, { uid: 4 }];
const arr2 = [
{
text: '随便1',
children: [{ uid: 1 }, { uid: 2 }],
},
{
text: '随便2',
children: [{ uid: 3 }, { uid: 4 }],
},
{
text: '随便3',
children: [{ uid: 5 }, { uid: 6 }],
},
];
预期数组
javascript">arr2 = [
{
text: '随便1',
children: [
{uid: 1, checked: false},
{uid: 2, checked: true}
]
},
{
text: '随便2',
children: [
{uid: 3, checked: true},
{uid: 4, checked: true}
]
},
{
text: '随便3',
children: [
{uid: 5, checked: false},
{uid: 6, checked: false}
]
}
]
答案
这里提两种方案,一种是直接改变arr2
数组本身的,一种是返回一个新数组的。
返回新数组
javascript">const fn = (source, target) => {
return target.map(item => {
return {
...item,
children: item.children.map(item1 => {
return {
uid: item1.uid,
isChecked: source.some(item2 => item2.uid === item1.uid),
};
}),
};
});
};
console.log(fn(arr1, arr2));
写这篇博客的目的就在于此,重温map
的用法。首先,map的callback必须有返回值,这些返回值回组成一个新的数组。如果想题目中那样得到预期数组且不改变原数组,则首先想到的就是map。原数组的每一项都是对象,则要想原数组的属性利用解构...
copy过来,其中的属性是应用类型的话,要再一次进行map。总之,如果用map产生新的对象数组,则要有深拷贝思想。
直接修改数组
javascript">const fn = (source, target) => {
target.forEach(item => {
item.children.forEach(child => {
child.isChecked = source.some(item1 => item1.uid === child.uid);
});
});
};
这种方法比较简单,笔者就不多说了。
欢迎批评指正!