I have a javascript object which has the nested array called interaction, now what I wanted to do is a loop from each object of the main array and fetch the values from the interaction array, I'm a kind of a newbie with iteration and looping. here below is the object
var data = [{
'id':'1',
'boothid':[{'id':'1','name':'yyy'}],
'interaction':[{
'userid':'1',
'username':'user1',
},{
'userid':'2',
'username':'user2',
}]
},
{
'id':'2',
'boothid':[{'id':'2','name':'xxx'}],
'interaction':[{
'userid':'4',
'username':'user4',
},
{
'userid':'5',
'username':'user5',
},
{
'userid':'6',
'username':'user6',
}],
'resource':'2',
},
{
'id':'3',
'boothid':[{'id':'2','name':'zzz'}],
'interaction':[{
'userid':'4',
'username':'user4',
}],
'resource':'3',
}]
console.log(data);
expected output
yyy
{
"userid": "1",
"username": "user1"
}
{
"userid": "2",
"username": "user2"
}
xxx
{
"userid": "4",
"username": "user4"
}
{
"userid": "5",
"username": "user5"
}
{
"userid": "6",
"username": "user6"
}
zzz
{
"userid": "4",
"username": "user4"
}
here what I'm trying to achieve is, I want to loop from the data object and show that in the frontend, so basically the output will be in 3 tables with respected booth names ex: table1= xxx, table2=yyy, table3=zzz, and the users in a particular booth will be displayed at td of theirs table.
You can use a .map
. I made some assumptions:
boothid
array has always one entry. I'll assume this is always the case.The code:
let data = [{id:'1',boothid:[{id:'1',name:'yyy'}],interaction:[{userid:'1',username:'user1',},{userid:'2',username:'user2',}]},{id:'2',boothid:[{id:'2',name:'xxx'}],interaction:[{userid:'4',username:'user4',},{userid:'5',username:'user5',},{userid:'6',username:'user6',}],resource:'2',},{id:'3',boothid:[{id:'2',name:'zzz'}],interaction:[{userid:'4',username:'user4',}],resource:'3',}];
let result = data.map(o => ({
boothname: o.boothid[0].name,
interactions: o.interaction.map(({username}) => ({ username }))
}));
console.log(result);