Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5679

Object destructuring to a named object

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: '',
};

Upvotes: 1

Views: 72

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

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);

Upvotes: 2

Related Questions