[英]pushing new objects to array results in mutation of existing object
我試圖創建一個.forEach()
其中,用於每個user
在對象users
的某些特性user
被映射然后被推到players
陣列除了海誓山盟新對象。
但是在我的嘗試中, user
所有結果都堆疊到一個對象中。 如何確保每個.push()
為每個user
創建一個新對象
我想要的是
[
{
name: 'Johnny',
id: '123456789',
lives: 3
},
{
name: 'Timmy',
id: '987654321',
lives: 3
},
]
我得到什么
[
{
name: [ 'Johnny', 'Timmy' ],
id: [ '123456789', '987654321' ],
lives: 3
}
]
代碼
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)
您可以通過簡單的地圖調用來完成此操作。 我想你想要更像的東西:
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.