简体   繁体   English

JavaScript - 将值从数组添加到嵌套 object

[英]JavaScript - Add values from array to nested object

I want to create a final object structure, as shown below.我想创建一个最终的 object 结构,如下图所示。

let finalArr = {
    "friends": 
    [
        {
            "name": 'Jake',
            "friendsList": [
                "Friend1",
                "Friend2",
                "Friend3"
            ]
        },
    ]
}

I start with this我从这个开始

let finalArr = {
      "friends": [
     ]
}

In a loop, I obtain data and store it into an Array, like this在一个循环中,我获取数据并将其存储到一个数组中,就像这样

[
  {
    name: 'Jake',
    friendsList: [
      'Friend1',
      'Friend2',
      'Friend3',
    ]
  },

How do I add the array I generate from the loop to the object, so that I can obtain the final structure that I want above?如何将我从循环中生成的数组添加到 object 中,以便获得上面想要的最终结构? I tried Json.push but that doesn't seem to work, nor does a regular loop and plug, as that gives me out of bounds issues.我试过Json.push但这似乎不起作用,常规循环和插头也不起作用,因为这给了我超出范围的问题。

You can access an object using bracket.您可以使用支架访问 object。

So, use finalArr.friends.push instead of Json.push所以,使用finalArr.friends.push而不是Json.push

finalArr.friends.push({
    name: 'Jake',
    friendsList: [
      'Friend1',
      'Friend2',
      'Friend3',
    ]
  })

simply you can push your object into friends array只需将 object 推入好友数组即可

let finalArr = {
  "friends": [
 ]
}
for(let i=0;i<3;i++){
finalArr.friends.push({
    name: 'Jake',
    friendsList: [
      'Friend1',
      'Friend2',
      'Friend3',
    ]
  })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM