-1

Destructuring an object: const p = {...this.props}, I can access any property with p.propertyNameX, p.propertyNameY, etc..

I would prefer to simply use propertyNameX and not use p.propertyNameX.

Can this be done without having to name all properties of the object like const {propertNameX, propertyNameY, etc...} = {...this.props}?

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58

1 Answers1

3

There is not really an option to just copy all your object fields to current scope variables without naming them separately.

But depending on what you want to achieve there are few other options.

I would strongly recommend you to refractor your code so you won't have to do that, but if it is some short, prototype code you can easily assign all object's properties to global like this:

for ( let prop in p ) {
    global[prop] = p[prop];
}

after that, all of properties can be accesed just like a regular variable, so in your example you can now do

console.log(propertyNameX);

and property (now global variable) value will be displayed in console.

but keep in mind, this will not set this in your current scope, but as global application values, as side-effect overriding any of previous global variables and making them accessible everywhere. Using global variables is an anty-pattern.