Mohan Aravind
Mohan Aravind

Reputation: 53

JavaScript - Add values from array to nested object

I want to create a final object structure, as shown below.

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? 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.

Upvotes: 1

Views: 66

Answers (2)

Ammar Yaqoob
Ammar Yaqoob

Reputation: 71

simply you can push your object into friends array

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

Upvotes: 0

LogiStack
LogiStack

Reputation: 1006

You can access an object using bracket.

So, use finalArr.friends.push instead of Json.push

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

Upvotes: 1

Related Questions