How can I clone a JavaScript object except for one key?
If you use Babel you can use the following syntax to copy property b from x into variable b and then copy rest of properties into variable y:
let x = {a: 1, b: 2, c: 3, z:26};
let {b, ...y} = x;
and 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"]);
var clone = Object.assign({}, {a: 1, b: 2, c: 3});
delete clone.b;
or if you accept property to be undefined:
var clone = Object.assign({}, {a: 1, b: 2, c: 3}, {b: undefined});
I use this ESNext one liner
const obj = { a: 1, b: 2, c: 3, d: 4 }
const clone = (({ b, c, ...o }) => o)(obj) // remove b and c
console.log(clone)
To add to Ilya Palkin's answer: you can even dynamically remove keys:
const x = {a: 1, b: 2, c: 3, z:26};
const objectWithoutKey = (object, key) => {
const {[key]: deletedKey, ...otherKeys} = object;
return otherKeys;
}
console.log(objectWithoutKey(x, 'b')); // {a: 1, c: 3, z:26}
console.log(x); // {a: 1, b: 2, c: 3, z:26};
Demo in Babel REPL
Source:
- https://twitter.com/ydkjs/status/699845396084846592