Search code examples
javascriptjavascript-objects

Copy out a child Object in JavaScript


I'm trying to copy out a child Object into a variable, but it seems that by simply declaring it, only the key get's copied. How do I copy out the entire Object? Here's what I'm trying...

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

Solution

  • use Object.assign

    DEMO

    const baseObj = {
      players: {
        player1: {
          name: "hello",
          details: "something"
        } 
      }
    }
    
    let cloned = Object.assign({}, baseObj.players.player1); 
    
    console.log(cloned);