编程语言
首页 > 编程语言> > 用JavaScript复制出一个子对象

用JavaScript复制出一个子对象

作者:互联网

我试图将一个子对象复制到一个变量中,但是似乎仅通过声明它,就只复制了键get.如何复制整个对象?这是我正在尝试的…

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

解决方法:

使用Object.assign

演示

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

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

console.log(cloned);

标签:javascript-objects,javascript
来源: https://codeday.me/bug/20191025/1930027.html