[英]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.我试图创建一个
.forEach()
其中,用于每个user
在对象users
的某些特性user
被映射然后被推到players
阵列除了海誓山盟新对象。
However in my attempt, all the results of user
stack into one object.但是在我的尝试中,
user
所有结果都堆叠到一个对象中。 How can I make sure each .push()
creates a new object for each user
如何确保每个
.push()
为每个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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.