prefer-destructuring

Require destructuring to read a property or an element into a variable

fixable

const name = user.name writes name twice. const { name } = user writes it once, and the next property you need goes into the same statement.

A property is only reported if the variable has the same name. An element is only reported if the index is a whole number written out, such as items[0].

--fix rewrites const name = user.name. Elements and plain assignments are reported but not fixed.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"prefer-destructuring" = "error" # or "warn"

Every option, set to its default. The ones that are commented out are unset by default.

bunfig.toml
[lint.rules]
"prefer-destructuring" = [
  "error",
  {
    object = true,
    array = true,
    # VariableDeclarator = <object>,
    # AssignmentExpression = <object>,
  },
  {
    enforceForRenamedProperties = false,
  },
]

Examples#

example.js3 problems
const name = user.name;
const first = items[0];
email = user.email;
example.jsNo problems
const { name } = user;
const [first] = items;
({ email } = user);

const label = user.name;
const current = items[index];
const city = user?.city;

Options#

The rule takes two objects. The first says what to check, and the second holds enforceForRenamedProperties.

bunfig.toml
[lint.rules]
prefer-destructuring = [
  "error",
  { object = true, array = false },
  { enforceForRenamedProperties = true },
]
OptionDefaultWhat it does
objecttrueReport properties: const name = user.name.
arraytrueReport elements: const first = items[0].
enforceForRenamedPropertiesfalseAlso report a property that goes into a variable with a different name, and a computed key.

If you pass the first object, a key you leave out is false.

example.jswith { "object": true }No problems
const first = items[0];
example.jswith { "object": true }, { "enforceForRenamedProperties": true }2 problems
const label = user.name;
const value = settings[key];

To treat declarations and assignments differently, give the first object the keys VariableDeclarator and AssignmentExpression, each with its own object and array:

example.jswith { "VariableDeclarator": { "object": true, "array": true }, "AssignmentExpression": { "object": false, "array": false } }No problems
email = user.email;
first = items[0];
example.jswith { "VariableDeclarator": { "object": true, "array": true }, "AssignmentExpression": { "object": false, "array": false } }1 problem
const email = user.email;