How to fix Eslint error "prefer-destructuring"?

JavascriptEcmascript 6Eslint

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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".

Solution 3 - Javascript

It's telling you to use

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimo ErnstView Question on Stackoverflow
Solution 1 - JavascriptBadis MerabetView Answer on Stackoverflow
Solution 2 - JavascriptilmironsView Answer on Stackoverflow
Solution 3 - JavascriptBergiView Answer on Stackoverflow