简体   繁体   中英

pushing new objects to array results in mutation of existing object

I am trying to create a .forEach() in which for every user object in users , certain properties of user are mapped then pushed to players array as new objects apart from eachother.

However in my attempt, all the results of user stack into one object. How can I make sure each .push() creates a new object for each user

What I Want

[
  {
    name: 'Johnny',
    id: '123456789',
    lives: 3
  },

  {
    name: 'Timmy',
    id: '987654321',
    lives: 3
  },
]

What I Get

[
  {
    name: [ 'Johnny', 'Timmy' ],
    id: [ '123456789', '987654321' ],
    lives: 3
  }
]

Code

let players = []
const users = {...}
                
users.forEach(user => {
   let username = user.map(user => user.username)
   let id = user.map(user => user.id)

   players.push({ name: username, id: id, lives: 3 })
})
                
console.log(players)

You can accomplish this with a simple map call. I think you want something more like:

 const users = [ { username: 'alice', id: 123 }, { username: 'bob', id: 456 }, ] const players = users.map(user => ({ name: user.username, id: user.id, lives: 3 })) console.log(players);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM