javascriptecmascript-6eslintobject-destructuring

Omit property variable when using object destructuring


Here is an example:

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

const { a, ...rest } = initObject

We're omitting property a from the object, but then const a is assigned a value, but never used - error from eslint (no-unused-vars). Is it possible to completely omit const a?


Solution

  • 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);