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

如何动态遍历JS嵌套数组 无需硬编码子数组位置按索引对应取值

优化方案

核心思路是把字段规则和遍历逻辑拆分,后续增减嵌套子数组只需调整规则配置,不需要修改遍历逻辑,完全去除硬编码索引。

完整可运行代码

const nestedArr = [
  [
    "COCA - COLA ORIGINAL 355 ML VIDRIO RET",
    "COCA - COLA ORIGINAL 600 ML PET NR",
    "COCA - COLA ORIGINAL 2.5 LT RET"
  ],
  [
    "$176.02",
    "$100.00",
    "$130.00"
  ],
  [
    "10",
    "3",
    "15"
  ]
]

// 字段规则配置,顺序和nestedArr的子数组顺序一一对应,新增子数组只需在此处添加配置
const fieldRules = [
  { key: 'name', formatter: val => val },
  { key: 'price', formatter: val => Number(val.replace('$', '')) },
  { key: 'qty', formatter: val => val }
]

const ordersObj = []
for (let i = 0; i < nestedArr[0].length; i++) {
  const currentItem = {}
  // 自动遍历所有子数组,按规则生成字段
  for (let j = 0; j < fieldRules.length; j++) {
    const { key, formatter } = fieldRules[j]
    currentItem[key] = formatter(nestedArr[j][i])
  }
  currentItem.amount = currentItem.price * currentItem.qty
  ordersObj.push(currentItem)
}

通用简化方案(无需预定义字段)

如果不需要提前指定字段名,只是要按索引聚合每个子数组的对应元素,可以直接用二维数组转置逻辑:

// 转置后得到[[商品1名称, 商品1价格, 商品1库存], [商品2名称, 商品2价格, 商品2库存]...]的结构
const transposedArr = nestedArr[0].map((_, index) => nestedArr.map(subArr => subArr[index]))

内容的提问来源于stack exchange,提问作者CAPOH A.C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:06:02