1

I'm trying to destructure an object using the following code.

const searchdata = {
    org,
    packageName,
    description,
    keywords
} = this.state;

but I get the following error.

Uncaught ReferenceError: org is not defined

What am I doing wrong here? could we destruture and object into another named object?

added a sample of the state object

this.state = {
    searchKey: '',
    onValueChange: false,
    org: '',
    packageName: '',
    description: '',
    keywords: '',
};
Imesh Chandrasiri
  • 5,558
  • 15
  • 60
  • 103
  • updated the question – Imesh Chandrasiri Apr 17 '18 at 09:41
  • 4
    Not in one step, no. You could desctructure into the separate parts *then* assign them back into an object using shorthand: `const { org, packageName, description, keywords } = this.state; const searchData = { org, packageName, description, keywords };`. Or use an immediately-invoked function to do it per the dupe I just linked. – jonrsharpe Apr 17 '18 at 09:43
  • it's not the case. When I remove the `searchdata` assignment, it works perfectly. – Imesh Chandrasiri Apr 17 '18 at 09:43
  • Possible duplicate of [How to get a subset of a javascript object's properties](https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties) – jonrsharpe Apr 17 '18 at 09:44
  • @ImeshChandrasiri Please, provide reproducible example. Code that you provided works fine. – Grigoriy Mikhalkin Apr 17 '18 at 09:44
  • Wrap in parentheses like `const searchdata = ({org, packageName...} = this.state)` – The Reason Apr 17 '18 at 09:46
  • @jonrsharpe you can do it in a one step. He needs to wrap a right assignment into parentheses – The Reason Apr 17 '18 at 09:48
  • 2
    @TheReason for me that gives you all of the content of `this.state` in `searchData`. – jonrsharpe Apr 17 '18 at 09:49
  • well I managed to do it using the following code. `const searchData = ((org, packageName, description, keywords) => (org, packageName, description, keywords))(this.state);` but is there a more cleaner way? – Imesh Chandrasiri Apr 17 '18 at 09:51
  • @jonrsharpe yeap you are right – The Reason Apr 17 '18 at 09:52

1 Answers1

2

You can do it by way of elimination using object rest:

const state = {
  searchKey: '',
  onValueChange: false,
  org: '',
  packageName: '',
  description: '',
  keywords: '',
};

const {
  searchKey,
  onValueChange,
  ...searchdata
} = state;

console.log(searchdata);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • This looks like almost perfect but isn't it unnecessary to define variables that are not needed? – Imesh Chandrasiri Apr 17 '18 at 09:55
  • 2
    This is how you omit stuff from an object using destructuring. It's a popular pattern and ESLint added an [option to allow it](https://eslint.org/docs/rules/no-unused-vars#ignorerestsiblings). – Ori Drori Apr 17 '18 at 09:58