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

如何将两个等长数组转换为指定格式的JSON对象数组?

解决方案

你可以通过以下几种JavaScript方法实现需求:

方法1:使用Array.map(简洁高效)

map方法会遍历数组并返回新数组,刚好适配这种一一对应的转换场景:

var arr1 = ["1", "2", "3", "4", "5", "6", "7", "8"];
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"];

const result = arr1.map((idStr, index) => ({
  id: parseInt(idStr, 10), // 将字符串ID转为数字
  chan: arr2[index]        // 取对应索引的频道名称
}));

console.log(result);

方法2:使用for循环(直观易懂)

如果更习惯传统循环写法,也可以手动构建结果数组:

var arr1 = ["1", "2", "3", "4", "5", "6", "7", "8"];
var arr2 = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"];

const result = [];
for (let i = 0; i < arr1.length; i++) {
  result.push({
    id: Number(arr1[i]), // 用Number转换字符串为数字也可
    chan: arr2[i]
  });
}

console.log(result);

两种方法最终都会生成你需要的格式:

[{id:1,chan:"discovery"},{id:2,chan:"nationalgeographic"},{id:3,chan:"hbo"},{id:4,chan:"wb"},{id:5,chan:"comedycentral"},{id:6,chan:"pogo"},{id:7,chan:"cnn"},{id:8,chan:"romedynow"}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:24:24