1

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.

mplungjan
180k29 gold badges183 silver badges246 bronze badges
asked Dec 2, 2020 at 7:37
3
  • There is no JSON here. It is a POJO and what is Json.push ? Commented Dec 2, 2020 at 7:40
  • 1
    finalArr.friends.push(yourObject) Commented Dec 2, 2020 at 7:40
  • Oops, that was a mistake my bad. Meant finalArr.friends.push wasn't working, but its because I was doing something dumb Commented Dec 2, 2020 at 7:49

2 Answers 2

1

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',
 ]
 })
mplungjan
180k29 gold badges183 silver badges246 bronze badges
answered Dec 2, 2020 at 7:40
Sign up to request clarification or add additional context in comments.

4 Comments

JSON is a STRING NOTATION format, you have an object
@mplungjan the object can be serialized as JSON.
@mplungjan Ah. Right. :)
@john Yes but that is irrelevant to the issues here
0

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',
 ]
 })
}
answered Dec 2, 2020 at 7:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.