javascript - Push an new object in an existing object in a loop -


i'm looping through json , trying push new object in existing 'master' object on each iteration. basically, i'm looking push method push objects objects instead of pushing them in array.

this push 1 object in local object.

var local = {}; (let = 0; < data[2].length; i++) {             let friend = {};             friend.name = data[2].users[i][0].name;             friend.screenname =  data[2].users[i][0].name;             friend.avatar =  data[2].users[i][0].name;               local["friend"] = friend;         }; 

ideally, want final local object like:

{ friend:     { name: '123',      screenname: '123',      avatar: '123' },    { name: '123',      screenname: '123',      avatar: '123' },    { name: '123',      screenname: '123',      avatar: '123' },       { name: '123',      screenname: '123',      avatar: '123' } } 

simply use array of friends:

var local = {  friends:[]//an array of friends }; (let = 0; < data[2].length; i++) {             let friend = {};             friend.name = data[2].users[i][0].name;             friend.screenname =  data[2].users[i][0].name;             friend.avatar =  data[2].users[i][0].name;             local.friends.push(friend);  }; 

or maybe easier using map:

var local={   friends:data[2].users.map(el=>({     name:el.name,     screenname:el.name,     avatar:el.name   })) }; 

so structure emerges result:

 {    friends: [      { name: '123',        screenname: '123',        avatar: '123' },     { name: '123',       screenname: '123',       avatar: '123' },     { name: '123',       screenname: '123',       avatar: '123' },       { name: '123',      screenname: '123',      avatar: '123' }  ]  } 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

.htaccess - ERR_TOO_MANY_REDIRECTS htaccess -