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.
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',
]
})
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',
]
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.