2017-10-15 81 views
3

我試圖將一個子對象拷貝到一個變量中,但似乎只是簡單地聲明它,只有拷貝的關鍵字被拷貝了。我如何複製整個對象?這裏就是我想...在JavaScript中拷貝一個子對象

const baseObj = { 
    players: { 
    player1: { 
     name: "hello", 
     details: "something" 
    }, 
    player2: ... 
    } 
} 

const player1Copy = baseObj.players.player1 
// I want to grab out the whole object player1 instead of just the key 

回答

4

使用Object.assign

DEMO

const baseObj = { 
 
    players: { 
 
    player1: { 
 
     name: "hello", 
 
     details: "something" 
 
    } 
 
    } 
 
} 
 

 
let cloned = Object.assign({}, baseObj.players.player1); 
 

 
console.log(cloned);

+2

替代現代JS'讓克隆= {... baseObj。 players.player1}; ' –