Search code examples
javascriptecmascript-6ecmascript-harmonyecmascript-2016

How can I clone a JavaScript object except for one key?


I have a flat JS object:

{a: 1, b: 2, c: 3, ..., z:26}

I want to clone the object except for one element:

{a: 1, c: 3, ..., z:26}

What's the easiest way to do this (preferring to use es6/7 if possible)?


Solution

  • There is a Destructuring assignment syntax in JavaScript that can be used

    let obj = {a: 1, b: 2, c: 3, z:26};
    let {b, ...rest} = obj;
    
    // skips the "Unused variable" warning
    let {b: _, ...rest} = obj;
    
    // removes property based on the dynamic key
    const dynamicKey = "b";
    let {[dynamicKey]: _, ...rest} = obj;
    

    Modern browsers already support it out of the box. See: JavaScript operator: Destructuring assignment: Rest in objects

    For old browser versions there is an option to use Babel to support destructuring assignment. It will be transpiled into:

    "use strict";
    
    function _objectWithoutProperties(obj, keys) {
      var target = {};
      for (var i in obj) {
        if (keys.indexOf(i) >= 0) continue;
        if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
        target[i] = obj[i];
      }
      return target;
    }
    
    var x = { a: 1, b: 2, c: 3, z: 26 };
    var b = x.b;
    
    var y = _objectWithoutProperties(x, ["b"]);