如何将两个数组合并为由对应元素构成的单个对象数组?
解决方案:将两个数组合并为对应元素的对象数组
方法一:使用数组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
相关产品推荐
相关产品推荐

