You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将两个等长数组的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 00:00:00