JavaScript如何将两个索引对应的数组合并为指定结构对象数组
按索引合并两个JavaScript数组的实现方案
问题场景
现有两个JavaScript数组:
const dateArray = ['January', 'February', 'March', 'April', 'May', 'June'] const InfoArray = [ { Date : '2022-01', Active: 1 }, { Date : '2022-02', Active: 12 }, { Date : '2022-03', Active: 25 }, { Date : '2022-04', Active: 33 }, { Date : '2022-05', Active: 120 }, { Date : '2022-06', Active: 335 }, ]
需要将两个数组按索引一一对应合并为对象数组:dateArray的元素作为新对象的month字段值,对应位置取InfoArray元素中的Active字段值,预期输出结构如下:
const result = [ { month: 'January', Active: 1 }, { month: 'February', Active: 12 }, { month: 'March', Active: 25 }, { month: 'April', Active: 33 }, { month: 'May', Active: 120 }, { month: 'June', Active: 335 }, ]
原有实现代码无法得到预期结果:
const makeObjectWithTwoArray = () => { let chartObj = {} dateArray.forEach((element, index) => { chartObj[element] = infoArray[index] }) return chartObj }
原有代码问题
- 初始定义的
chartObj是普通对象,最终返回的是键值对结构,不符合要求的数组返回值 - 赋值逻辑直接将
InfoArray的完整元素作为属性值,既没有提取需要的Active字段,也没有生成要求的month字段结构
正确实现
直接使用Array.map遍历即可,map会按索引遍历数组、返回和原数组长度一致的新数组,完全匹配当前按索引合并的需求:
const makeObjectWithTwoArray = () => { return dateArray.map((month, index) => ({ month, Active: InfoArray[index].Active })) }
如果两个数组可能存在长度不一致的情况,可以加容错逻辑,避免访问不存在元素的属性时报错:
const makeObjectWithTwoArray = () => { return dateArray.map((month, index) => ({ month, Active: InfoArray[index]?.Active ?? 0 // 无匹配项时默认Active为0,可按需调整默认值 })) }
内容的提问来源于stack exchange,提问作者Aden Lee
相关产品推荐
相关产品推荐

