You need to enable JavaScript to run this app. 在JavaScript中如何将两个数组合并为一个对象数组
优惠活动
大模型
产品
解决方案
定价
更多

在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 05:09:04