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

如何将二维数组转换为对象数组?代码实现出错求助

二维数组转对象数组的错误修正

问题场景

尝试用forEach和push将二维数组转为对象数组,但输出结果不符合预期。

原始代码

const dummyArray = [
  [45292, 1, 2],
  [46292, 5, 6],
  [47292, 9, 10],
]

const resultArray: any[] = []

dummyArray.forEach((elementValue, index) => {
  resultArray.push({ date: '', price: '', code: '' })

  elementValue.forEach(value => {
    if (index === 0) {
      resultArray[index] = { ...resultArray[index], date: value }
    }
    if (index === 1) {
      resultArray[index] = { ...resultArray[index], price: value }
    }
    if (index === 2) {
      resultArray[index] = { ...resultArray[index], code: value }
    }
  })
})

console.log('resultArray', resultArray)

当前输出

[
  { date: 2, price: '', code: ''},
  { date: '', price: 6, code: ''},
  { date: '', price: '', code: 10},
]

期望输出

[
  { date: 45292, price: 1, code: 2},
  { date: 46292, price: 5, code: 6},
  { date: 47292, price: 9, code: 10},
]

错误原因

原代码内层forEach误用了外层子数组的索引来判断赋值字段:比如第一个子数组(索引0)的所有元素都会覆盖date字段,最后date只保留子数组最后一个值;同理其他子数组也只保留对应字段的最后一个值,完全不符合预期映射逻辑。

正确的逻辑应该是根据元素在子数组中的位置来匹配对象的对应字段。


修正方案

方案1:基于原代码调整(保留forEach写法)

直接解构子数组元素,或者在内层循环中使用子数组内的元素索引:

const dummyArray = [
  [45292, 1, 2],
  [46292, 5, 6],
  [47292, 9, 10],
]

const resultArray: any[] = []

dummyArray.forEach(element => {
  // 解构子数组的三个元素,直接对应对象字段
  const [date, price, code] = element
  resultArray.push({ date, price, code })
})

console.log('resultArray', resultArray)

如果一定要用双层forEach:

const dummyArray = [
  [45292, 1, 2],
  [46292, 5, 6],
  [47292, 9, 10],
]

const resultArray: any[] = []

dummyArray.forEach(element => {
  const newObj = { date: '', price: '', code: '' }
  element.forEach((value, idx) => {
    // 根据元素在子数组中的索引赋值
    if (idx === 0) newObj.date = value
    if (idx === 1) newObj.price = value
    if (idx === 2) newObj.code = value
  })
  resultArray.push(newObj)
})

console.log('resultArray', resultArray)

方案2:用map简化代码(推荐)

map方法专为数组转换设计,代码更简洁高效:

const dummyArray = [
  [45292, 1, 2],
  [46292, 5, 6],
  [47292, 9, 10],
]

// 解构子数组元素并直接返回对象
const resultArray = dummyArray.map(([date, price, code]) => ({ date, price, code }))

console.log('resultArray', resultArray)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:55:37