JavaScript:如何通过解构从嵌套对象复制一些键

Out*_*ker 4 javascript destructuring ecmascript-6

说我有一个对象:

myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2', three: '3'} // (Edited) Added one more key here :)
};
Run Code Online (Sandbox Code Playgroud)

我想要此对象的副本,但不具有指向新对象的某些键,其输出方式如下:

newObj = { 
      name: 'Luke',
      age: 12,
      one: '1',
      two: '2'
    };
Run Code Online (Sandbox Code Playgroud)

我已经看到了破坏的例子,但是我想知道嵌套对象是否有可能。使用解构是否可以实现这样的目的,否则,将是最有效的方法吗?

Dac*_*nny 5

用类似于destruct的语法实现此目的的一种方法是这样的:

const myObj = { 
  name: 'Luke',
  age: 12,
  height: '163cm',
  weight: '60kg',
  others: { one: '1', two: '2', three : '3'}
};


const newObj = {
  /* Copy over values from "myObj" to equivalent keys in "newObj" */
  name : myObj.name,
  age : myObj.age,

  /* Spread keys "one" and "two" of the nested "others" object into "newObj" */
  ...({one, two} = myObj.others, {one, two})
}

console.log(newObj)
Run Code Online (Sandbox Code Playgroud)