diff --git a/docs/rules/prefer-destructuring.md b/docs/rules/prefer-destructuring.md index 00b55774b21..7f18559ed50 100644 --- a/docs/rules/prefer-destructuring.md +++ b/docs/rules/prefer-destructuring.md @@ -21,6 +21,8 @@ The rule has a second object with a single key, `enforceForRenamedProperties`, w - Accessing an object property whose key is an integer will fall under the category `array` destructuring. - Accessing an array element through a computed index will fall under the category `object` destructuring. +The `--fix` option on the command line fixes only problems reported in variable declarations, and among them only those that fall under the category `object` destructuring. Furthermore, the name of the declared variable has to be the same as the name used for non-computed member access in the initializer. For example, `var foo = object.foo` can be automatically fixed by this rule. Problems that involve computed member access (e.g., `var foo = object[foo]`) or renamed properties (e.g., `var foo = object.bar`) are not automatically fixed. + Examples of **incorrect** code for this rule: ```javascript diff --git a/lib/rules/prefer-destructuring.js b/lib/rules/prefer-destructuring.js index d3314dc7e0d..66e412fd3e3 100644 --- a/lib/rules/prefer-destructuring.js +++ b/lib/rules/prefer-destructuring.js @@ -163,6 +163,8 @@ module.exports = { return node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init.type === "MemberExpression" && + !node.init.computed && + node.init.property.type === "Identifier" && node.id.name === node.init.property.name; } diff --git a/tests/lib/rules/prefer-destructuring.js b/tests/lib/rules/prefer-destructuring.js index 7795ed85b75..3b7c0183db8 100644 --- a/tests/lib/rules/prefer-destructuring.js +++ b/tests/lib/rules/prefer-destructuring.js @@ -237,6 +237,16 @@ ruleTester.run("prefer-destructuring", rule, { type: "VariableDeclarator" }] }, + { + code: "var foo = object[foo];", + output: null, + options: [{ object: true }, { enforceForRenamedProperties: true }], + errors: [{ + messageId: "preferDestructuring", + data: { type: "object" }, + type: "VariableDeclarator" + }] + }, { code: "var foo = object['foo'];", output: null,