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
相关产品推荐
相关产品推荐

