Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 409
fox Avatar asked Jan 09 '16 21:01

fox


People also ask

How many ways can you clone an object in JavaScript?

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.


2 Answers

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}); 
like image 20
madox2 Avatar answered Sep 18 '22 13:09

madox2


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"]); 
like image 197
Ilya Palkin Avatar answered Sep 19 '22 13:09

Ilya Palkin