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

React JavaScript:将多数组转换为数组对象的实现需求

解决方案

你可以用Array.reduce()来快速构建目标对象,核心思路是遍历数组索引,把三个数组对应位置的元素组合成新数组,再挂载到以row+索引为键的对象上:

const dateArray = ["9/13/2022", "9/13/2022", "9/13/2022", "9/13/2022","9/13/2022"]
const timeArray = ["00:00", "00:01", "00:02", "00:03", "00:04"]
const integerArray = [1,2,3,4,5]

const result = dateArray.reduce((acc, _, index) => {
  acc[`row${index}`] = [dateArray[index], timeArray[index], integerArray[index]]
  return acc
}, {})

console.log(result)

关键说明

  • 初始值传入空对象{},作为累加器acc的起始状态
  • 遍历过程中用当前index同步获取三个数组对应位置的元素,组合成新数组
  • 给累加器添加row${index}属性并赋值,最终返回累加器得到目标结构
  • 注意:必须保证三个数组长度完全一致,否则会出现取值为undefined的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:50:24