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

JavaScript中如何将数组插入到对象数组multipleBranch内?

实现方案

场景1:还未初始化multipleBranch变量

直接在声明变量时赋值即可,ES6支持键值同名简写:

// 现有branches数组
const branches = [1,2,3,4,5,6,7,8,9,10]

// 完整写法
const multipleBranch = [
  {
    branches: branches
  }
]

// ES6简写(键名和变量名一致时可省略值)
// const multipleBranch = [{ branches }]

场景2:multipleBranch已经存在,需要新增对应对象

调用数组的push方法往末尾插入对象即可:

// 已存在的multipleBranch数组(示例为已初始化的空数组)
const multipleBranch = []
const branches = [1,2,3,4,5,6,7,8,9,10]

// 插入新对象
multipleBranch.push({ branches })

两种实现最终输出的multipleBranch结构都符合需求:

console.log(multipleBranch)
// 输出:
// [
//   {
//     branches: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
//   }
// ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:36:05