在JavaScript中如何将两个数组合并为一个对象数组
实现方法
你可以直接使用数组的map方法完成一一对应合并,该方案适用于两个数组长度一致、相同索引位置元素互相对应的场景:
const array1 = ['US', 'AG','In'] const array2 = ['flagIconUS','flagIconAG','flagIconIN'] // 基础写法 const array3 = array1.map((code, index) => { return { code: code.toUpperCase(), // 调用toUpperCase统一转大写,匹配你预期的输出格式 icon: array2[index] } }) // 箭头函数简写版本 // const array3 = array1.map((code, i) => ({ code: code.toUpperCase(), icon: array2[i] }))
如果两个数组长度不确定,为了避免生成属性值为undefined的无效元素,可以取两个数组的最小长度来生成结果:
const minLength = Math.min(array1.length, array2.length) const array3 = Array.from({ length: minLength }, (_, index) => ({ code: array1[index].toUpperCase(), icon: array2[index] }))
内容的提问来源于stack exchange,提问作者hemant kaushik
相关产品推荐
相关产品推荐

