55
votes

I wanted to shorten an object literal in ES6 like this:

const loc = this.props.local;

The reason is loc.foo(); is a lot easier to type than this.props.local.foo();

But now ESLint complains:

Use object destructuring: prefer-destructuring

I've read the error description on eslint.org but I don't understand it. They have an example which looks very similar to my code but theirs seem to be ok?

var foo = object.bar;

How can I fix the error without setting it to ignore in the .eslintrc file?

3
That's a rule one needs to enable in the first place. Why did you do that if you don't like it? - Bergi
That's not true. If one extends someone else's config, then you might have to disable this rule instead. - Merlin -they-them-
Sorry, forgot to mention I'm using Airbnb styleguide - Timo Ernst

3 Answers

93
votes

change your code from:

const local = this.props.local;

to:

const { local } = this.props;

They are equivalent and you can call local.foo() in the same way. except that the second use object destructuring.

5
votes

It's a new construct in ES 6 that allows you to match property of an object in assignment. The syntax you need is:

const { local: loc } = this.props

which translates to: "declare a constant loc and assign it the value of property local from this.props".

2
votes

It's telling you to use

const {props: {local: loc}} = this;