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

JavaScript中如何将两个数组合并为指定结构的对象?

合并数组为指定结构对象的实现方案

以下是两种常用开发语言的实现方式:

Python 实现

可以直接使用字典推导式配合zip()函数完成映射,代码如下:

players_name = ['John','Paul','Jack']
points = [23,13,18]
# 合并生成目标结构
players_results = {name: {'point': point} for name, point in zip(players_name, points)}

JavaScript 实现

可以使用数组的reduce()方法遍历姓名数组,结合索引匹配对应得分完成构造,代码如下:

const players_name = ['John','Paul','Jack'];
const points = [23,13,18];
// 合并生成目标结构
const players_results = players_name.reduce((resultObj, currentName, index) => {
  resultObj[currentName] = { point: points[index] };
  return resultObj;
}, {});

注意:操作前请确保两个数组长度一致,且相同索引位置的姓名和得分是一一对应的,避免出现映射错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 13:48:00