Omit property variable when using object destructuring

error from eslint (no-unused-vars).

The no-unused-vars rules has two configuration options that will help with your use case:

  • The ignoreRestSiblings option is a boolean that defaults to false. When enabled, the rest property’s siblings are ignored. This is exactly what you need!
  • The varsIgnorePattern option specifies a regexp pattern for variable names not to be checked for usage. This allows us to make an exception for the common underscore identifier to explicitly mark unused variables with { "varsIgnorePattern": "^_" }.

    const { a:_, ...rest } = initObject;
    //       ^^
    

    Unfortunately you still need to avoid multiple declarations of the _ variable, so to omit multiple properties you'd need to do something like { a:_a, b:_b, ...rest } = ….

Is it possible to completely omit const a?

A bad hack that completely avoids introducing any identifier would be to use

const { a:{}, ...rest } = initObject;
//       ^^^

that further destructures the .a property value into an object, but for this you need to ensure that the property exists and doesn't hold a null or undefined value.


A possible way is to use // eslint-disable-next-line no-unused-vars

e.g.

// eslint-disable-next-line no-unused-vars
const { a, ...rest } = initObject

Or by using ignoreRestSiblings

The ignoreRestSiblings option is a boolean (default: false). Using a Rest Property it is possible to “omit” properties from an object, but by default the sibling properties are marked as “unused”. With this option enabled the rest property’s siblings are ignored.

e.g.

/*eslint no-unused-vars: ["error", { "ignoreRestSiblings": true }]*/
// 'a' is ignored because it has a rest property sibling.
const { a, ...rest } = initObject;

More info about no-unused-vars


But if your goal is to remove the property a, there is another way.
You can use delete operator.

From MDN documentation

The JavaScript delete operator removes a property from an object

e.g.

const initObject = {
  a: 0,
  b: 0,
  c: 0
}

const rest = { ...initObject }; // create a shallow copy
delete rest.a;

console.log(rest);