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

如何将两个数组按对应值合并为指定结构的对象数组?

最优解决方案:使用JavaScript的map()方法

嘿,要实现两个数组按对应索引配对生成指定结构的数组,用JavaScript的map()方法绝对是最简洁高效的选择——它天生就是为这类数组转换场景设计的。

前提说明

首先我们默认两个数组的长度完全一致,并且对应索引位置的元素就是需要配对的源和目标值(这也是你给出示例的核心逻辑)。

完整代码实现

// 定义原始的源数组和目标数组
const sourcePGs = ["Isolated-1", "SVT_FedPortGroup", "SVT_StoragePortGroup", "VM Network", "test-pg-2002"];
const targetPGs = ["target_Isolated-1", "target_SVT_FedPortGroup", "target_SVT_StoragePortGroup","target_VM Network" ,"target_test-pg-2002"];

// 生成指定格式的NetworkMaps数组
const NetworkMaps = sourcePGs.map((sourcePG, index) => ({
  ENVID: null,
  SourcePG: sourcePG,
  TargetPG: targetPGs[index]
}));

console.log(NetworkMaps);

代码解释

  • map()方法会遍历sourcePGs数组的每一个元素,同时获取当前元素的索引index
  • 利用index可以精准获取targetPGs中对应位置的目标值
  • 每次遍历返回一个包含ENVID、SourcePG、TargetPG的对象,最终这些对象会被组合成新的数组返回

健壮性优化(可选)

如果担心两个数组长度不一致导致配对错误,可以先加个长度校验:

if (sourcePGs.length !== targetPGs.length) {
  throw new Error("源数组和目标数组长度不匹配,无法完成正确配对!");
}

// 之后再执行map逻辑

验证你的简单示例

用同样的逻辑处理你给出的测试用例:

const arr1 = ["a", "b", "c"];
const arr2 = ["apple", "ball", "cat"];

const result = arr1.map((source, index) => ({
  source: source,
  target: arr2[index]
}));

// 输出结果:[{source: "a",target: "apple"}, {source: "b",target: "ball"},{source: "c",target: "cat"}]

内容的提问来源于stack exchange,提问作者Jeet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:23:39