如何按索引合并两个对象数组,生成指定结构的新数组?
按索引合并两个对象数组的实现方案
需求说明
现有两个长度一致的对象数组:
const array1 = [ { image: 'image1', title: 'title1' }, { image: 'image2', title: 'title2' }, { image: 'image3', title: 'title3' }, ]; const array2 = [ { downloadLink: 'downloadLink1', fileName: 'fileName1' }, { downloadLink: 'downloadLink2', fileName: 'fileName2' }, { downloadLink: 'downloadLink3', fileName: 'fileName3' }, ];
需要按索引对应合并每个位置的对象,生成如下结构的新数组(仅保留image、downloadLink、fileName属性):
const array3 = [ { image: 'image1', downloadLink: 'downloadLink1', fileName: 'fileName1' }, { image: 'image2', downloadLink: 'downloadLink2', fileName: 'fileName2' }, { image: 'image3', downloadLink: 'downloadLink3', fileName: 'fileName3' }, ];
实现方案
方案1:使用Array.map()方法(推荐)
利用map遍历数组,结合展开运算符(...)合并对应索引的对象属性,同时筛选需要保留的字段:
const array3 = array1.map((item, index) => ({ image: item.image, ...array2[index] }));
如果需要保留array1的所有属性再移除不需要的字段(比如示例中的title),可以这样写:
const array3 = array1.map((item, index) => { const merged = { ...item, ...array2[index] }; delete merged.title; return merged; });
方案2:使用Array.forEach()循环
通过遍历数组索引,逐个合并对象并推入新数组:
const array3 = []; array1.forEach((item, index) => { array3.push({ image: item.image, ...array2[index] }); });
方案3:使用普通for循环
适用于需要兼容旧环境的场景,逻辑清晰直观:
const array3 = []; for (let i = 0; i < array1.length; i++) { array3.push({ image: array1[i].image, downloadLink: array2[i].downloadLink, fileName: array2[i].fileName }); }
内容的提问来源于stack exchange,提问作者Paco Zevallos
相关产品推荐
相关产品推荐

