如何将两个等长数组的key互相映射 其中一个为嵌套结构数组
实现思路
两个输入数组长度完全匹配,idListToInsert第N项的idToInsert字段值,就是otherObjectList第N个嵌套子数组所有元素需要统一新增的属性值。
你可以通过两层map遍历配合索引匹配完成需求,不需要修改原始数组的写法如下:
const idListToInsert = [{ idToInsert: 1 }, { idToInsert: 3 }, { idToInsert: 4 }]; const otherObjectList = [ [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }], [{ id: 5 }, { id: 6 }, { id: 7 }], [{ id: 8 }, { id: 9 }], ]; const targetList = otherObjectList.map((subArray, index) => { const insertValue = idListToInsert[index].idToInsert; return subArray.map(item => ({ ...item, idToInsert: insertValue })); });
如果你的业务场景不需要保留原始otherObjectList的对象数据,也可以直接修改原对象属性减少内存开销,写法如下:
otherObjectList.forEach((subArray, index) => { const insertValue = idListToInsert[index].idToInsert; subArray.forEach(item => item.idToInsert = insertValue); }); // 此时otherObjectList已经是你要的目标结构
内容的提问来源于stack exchange,提问作者dan_boy
相关产品推荐
相关产品推荐

