20

The is code works fine by destructuring the object and assigning the variables,

const { allowNegative, decimal, precision, prefix, suffix, thousands } = this.options;

But when i try with this operator like below it throws an error:

{ this.tabConfig, this.searchUiConfig, this.gridUiConfig } = CONFIG;

where CONFIG being a JSON. Error being [ts] Declaration or statement expected on the assignment operator(=).

Is there a better way of doing than this:

 this.tabConfig = CONFIG.tabConfig;
 this.searchUiConfig = CONFIG.searchUiConfig;
 this.gridUiConfig = CONFIG.gridUiConfig;
Sam Watkins
  • 7,819
  • 3
  • 38
  • 38
radio_head
  • 1,306
  • 4
  • 13
  • 28

1 Answers1

31

You can do it with the following syntax:

({ prop: this.prop } = obj);

Here I'm using a deep object matching

var obj = { propIwantFromObj: 'foo' };
var { propIwantFromObj: whereToStoreValue } = obj;

On the left part you will say which property you want to get from the object and on the right side you are going to say where to store the value. So in this case a new variable called whereToStoreValue will be created with foo value.

var obj = { propIwantFromObj: 'foo' };
var whereToStoreValue = obj.propIwantFromObj;

That can be used to store values on this (or other object), but you need to wrap it around parenthesis because of the .. For some reason this hack allows you to use ..

If you don't use the parenthesis you will get syntax errors (it won't work in pure JS either).

Example:

const CONFIG = {
  tabConfig: 1,
  searchUiConfig: 2,
  gridUiConfig: 3,
};

class Foo {
  bar() {
    ({ tabConfig: this.tabConfig, searchUiConfig: this.searchUiConfig, gridUiConfig: this.gridUiConfig } =  CONFIG);
  }
}

const foo = new Foo();
foo.bar();

console.log(foo.tabConfig);
console.log(foo.searchUiConfig);
console.log(foo.gridUiConfig);
BrunoLM
  • 97,872
  • 84
  • 296
  • 452