You need to enable JavaScript to run this app. 如何将两个长度不对称的数组转换为指定结构的对象数组?
优惠活动
大模型
产品
解决方案
定价
更多

如何将两个长度不对称的数组转换为指定结构的对象数组?

问题说明

卡了一整天始终无法推进解决进度,清楚只差一个小细节没考虑到,但始终找不到问题所在。
现有两个数组:

arrKeys = ["a", "b", "c"]
arrValues = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

期望最终得到如下结构的对象数组:

myObj = [
 {
  "a": 1,
  "b": 2,
  "c": 3
 },
 {
  "a": 4,
  "b": 5,
  "c": 6
 },
 {
  "a": 7,
  "b": 8,
  "c": 9
 }
]

尝试编写的实现代码如下:

const myObj = arrKeys.reduce((newObj, key, index) => {
  if (arrValues[index] == undefined) arrValues[index] = null
  newObj[key] = aarValues[index]
  return newObj
}, {})
cosnole.log(myObj)

当前实现存在两个核心问题:

  • arrKeys只会遍历一轮,不知道如何在arrKeys遍历到最大长度后重置计数器
  • 最终返回的只有单个对象,而非需要的对象数组,实际运行得到的结果如下:
myObj = {
  "a": 1,
  "b": 2,
  "c": 3
 }
解决方案

原实现的核心问题是遍历维度选错了:不应该遍历arrKeys生成单个对象,而是应该先按照arrKeys的长度,把arrValues拆分成多个等长的分组,每个分组和arrKeys做键值映射生成一个对象,最后把所有对象存入结果数组即可。
另外原代码存在两处笔误,修正逻辑前需要先改对:

  • 变量名aarValues拼写错误,正确为arrValues
  • 日志方法cosnole.log拼写错误,正确为console.log

易读的循环实现

逻辑最直观,新手也能一眼看懂:

const arrKeys = ["a", "b", "c"]
const arrValues = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const keyCount = arrKeys.length
const result = []

// 以key数组长度为步长遍历值数组,每次处理一组数据
for (let i = 0; i < arrValues.length; i += keyCount) {
  const groupObj = {}
  arrKeys.forEach((key, keyIndex) => {
    // 兼容值数组长度不足的场景,缺失值填null
    groupObj[key] = arrValues[i + keyIndex] ?? null
  })
  result.push(groupObj)
}

console.log(result)

reduce 写法实现

如果偏好函数式写法,可以用reduce归并值数组生成结果:

const arrKeys = ["a", "b", "c"]
const arrValues = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const keyCount = arrKeys.length

const myObj = arrValues.reduce((resultList, _, currentIndex) => {
  // 每遇到一组的起始索引(索引为key长度的整数倍),就新建一个分组对象
  if (currentIndex % keyCount === 0) {
    const groupObj = {}
    arrKeys.forEach((key, keyIndex) => {
      groupObj[key] = arrValues[currentIndex + keyIndex] ?? null
    })
    resultList.push(groupObj)
  }
  return resultList
}, [])

console.log(myObj)

两段代码运行后都能得到预期的对象数组结构。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:39:18