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

如何将两个数组合并为由对应元素构成的单个对象数组?

解决方案:将两个数组合并为对应元素的对象数组

方法一:使用数组map方法(推荐)

map方法可以便捷地遍历数组,同时结合索引获取另一个数组的对应元素,生成目标对象数组:

const words = ['Toolbar', 'Vamoose', 'Arcade'];
const clues = ['Strip of buttons', 'Get lost', 'Pinball wizards hangout'];

const output = words.map((word, index) => ({ [word]: clues[index] }));
console.log(output);

这段代码会遍历words数组的每个元素,以当前元素为键、clues数组对应索引的元素为值创建对象,最终返回由这些对象组成的数组。

方法二:使用for循环(适合基础理解)

如果更倾向于基础循环逻辑,for循环也能实现同样效果:

const words = ['Toolbar', 'Vamoose', 'Arcade'];
const clues = ['Strip of buttons', 'Get lost', 'Pinball wizards hangout'];
const output = [];

for (let i = 0; i < words.length; i++) {
  output.push({ [words[i]]: clues[i] });
}
console.log(output);

通过遍历索引,逐个创建对象并推入结果数组中。

处理数组长度不一致的情况

如果两个数组长度不同,可以添加判断逻辑避免报错或补充默认值:

const output = words.map((word, index) => ({
  [word]: clues[index] ?? 'No clue provided'
}));

这里使用空值合并运算符??,当clues[index]不存在时,使用默认文本作为值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:15:38