简体   繁体   中英

Destructuring Object with Enum in Javascript

I try to find a way to destructuring keys of the object in ES6 with keys of another object (Eum) and create variables. for example my enum is

const KEYS = {
  name:'name',
  family:'age'
}

and my object is :

const myObject = {
  name:'John',
  family:'Doe'
}

and what I want is destructuring myObject with keys of KEYS I know the below code is wrong but something like this :

 const {KEYS.name} = myObject

so it creates a variable with name name that is the value of KYES.name but as I say it raised a syntax error . does anyone has an idea for a destructuring object with an enum.

You could use a computed property names and an object property assignment pattern [YDKJS: ES6 & Beyond] for it.

name is a reserved property of window and may lead to unexpected results by changing it.

 const KEYS = { name: 'name', family: 'age' }, myObject = { name:'John', family:'Doe' }; ({ [KEYS.name]: window[KEYS.name] } = myObject); console.log(name); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM