Is this a good way to clone an object in ES6?

javascript copy object without reference
javascript deep copy object
typescript copy object
object.assign deep copy
object-assign polyfill
object-assign ie11
es6 deep copy
javascript extend object

Googling for "javascript clone object" brings some really weird results, some of them are hopelessly outdated and some are just too complex, isn't it as easy as just:

let clone = {...original};

Is there anything wrong with this?

This is good for shallow cloning. The object spread is a standard part of ECMAScript 2018.

For deep cloning you'll need a different solution.

const clone = {...original} to shallow clone

const newobj = {...original, prop: newOne} to immutably add another prop to the original and store as a new object.

3 Ways to clone objects in JavaScript - Better Programming, Cloning an object in JavaScript a task that is almost always used in any project, that would hurt you in the bones if you didn't know the proper way to do it. Almost all of them used a more complex version of iterationCopy before ES6 was​  The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. The source for this interactive example is stored in a GitHub repository.

EDIT: When this answer was posted, {...obj} syntax was not available in most browsers. Nowadays, you should be fine using it (unless you need to support IE 11).

Use Object.assign.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }

However, this won't make a deep clone. There is no native way of deep cloning as of yet.

EDIT: As @Mike 'Pomax' Kamermans mentioned in the comments, you can deep clone simple objects (ie. no prototypes, functions or circular references) using JSON.parse(JSON.stringify(input))

Object.assign(), But no worries, here are 3 ways for you to clone an object. const food Often time shallow copy is good enough, you don't really need a deep copy. It's like a  That’s it, we’re good to go! Installing Express. Using the Express generator, we will create a new project with generated code, move some files, and convert some code to ES6 syntax. We need to convert it at this early stage because we need a way to verify if our ES6 code works. Project Setup. Run this command in your terminal.

if you don't want to use json.parse(json.stringify(object)) you could create recursively key-value copies:

function copy(item){
  let result = null;
  if(!item) return result;
  if(Array.isArray(item)){
    result = [];
    item.forEach(element=>{
      result.push(copy(element));
    });
  }
  else if(item instanceof Object && !(item instanceof Function)){ 
    result = {};
    for(let key in item){
      if(key){
        result[key] = copy(item[key]);
      }
    }
  }
  return result || item;
}

But the best way is to create a class that can return a clone of it self

class MyClass{
    data = null;
    constructor(values){ this.data = values }
    toString(){ console.log("MyClass: "+this.data.toString(;) }
    remove(id){ this.data = data.filter(d=>d.id!==id) }
    clone(){ return new MyClass(this.data) }
}

3 Ways to Clone Objects in JavaScript, In this post we will discuss the different methods to copy the javascript object and discuss the outcome of each method. But before that just keep  @RyanCavanaugh While I don't know too much about the ES6 Spec, I found 4.3.31 method stating: When a function is called as a method of an object, the object is passed to the function as its this value.

If the methods you used isn't working well with objects involving data types like Date, try this

Import _

import * as _ from 'lodash';

Deep clone object

myObjCopy = _.cloneDeep(myObj);

Different methods to copy an object in JavaScript, Introduction; The Naive Way of Copying Objects; Shallow Copying Objects ES6 already has rest elements for array destructuring assignment and If you have any library or piece of code that achieves a better result, feel  There are a lot of different phone clone apps in the market with which you can clone a phone number, SIM card, or even text messages without touching the phone. In this article, we’ll discuss the 7 most effective ways to clone a Phone Number, SIM Card, or Text Messages. Read on to find out how to clone a phone without touching it.

Following on from the answer by @marcel I found some functions were still missing on the cloned object. e.g.

function MyObject() {
  var methodAValue = null,
      methodBValue = null

  Object.defineProperty(this, "methodA", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    },
    enumerable: true
  });

  Object.defineProperty(this, "methodB", {
    get: function() { return methodAValue; },
    set: function(value) {
      methodAValue = value || {};
    }
  });
}

where on MyObject I could clone methodA but methodB was excluded. This occurred because it is missing

enumerable: true

which meant it did not show up in

for(let key in item)

Instead I switched over to

Object.getOwnPropertyNames(item).forEach((key) => {
    ....
  });

which will include non-enumerable keys.

I also found that the prototype (proto) was not cloned. For that I ended up using

if (obj.__proto__) {
  copy.__proto__ = Object.assign(Object.create(Object.getPrototypeOf(obj)), obj);
}

PS: Frustrating that I could not find a built in function to do this.

Copying Objects in JavaScript ― Scotch.io, If any of the fields of the original object holds references to other objects, then only references of those objects are copied into clone object, copy  DataGrouper itself is a function. You can call it with your data and a list of the properties you want to group by. It returns an array whose elements are object with two properties: key is the collection of grouped properties, vals is an array of objects containing the remaining properties not in the key.

How To Easily Clone Es6 Object Cloning By Doing Less – Logic24by7, Note: Shallow copy is a bit-wise copy of an object. Using ES6, Libraries, JSON.​parse/stringify, and native methods Underscore is great. Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

Ways to Clone an Object in JavaScript, JavaScript offers many ways to copy an object, but not all provide deep copy. Lodash has this nice feature: you can import single functions separately in The spread operator is a ES6/ES2015 feature that provides a very  public abstract object Clone(); } Here's what MSDN says about ICloneable (emphasis mine): An implementation of Clone can perform either a deep copy or a shallow copy. In a deep copy, all objects are duplicated; in a shallow copy, only the top-level objects are duplicated and the lower levels contain references.

How to deep clone a JavaScript object, sources) . The target object is the first parameter and is also used as the return value. Object.assign() is useful for merging objects or cloning them 

Comments
  • this isn't legal ES6. But if it weren, this isn't a clone: both your clone and original properties point to the same things now. For instance, original = { a: [1,2,3] } gives you a clone with clone.a literally being original.a. Modification through either clone or original modifies the same thing, so no, this is bad =)
  • @AlbertoRivera It's kinda valid JavaScript, in that it's a stage 2 proposal that's likely to be a future addition to the JavaScript standard.
  • @Frxstrem with the question being about ES6, this is not valid JavaScript =)
  • Shallow or deep cloning?
  • You're right, it's not valid ES6, it's valid ES9. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • However, isn't this just a shallow clone? As in, properties are not cloned recursively, are they? Therefore, original.innerObject === clone.innerObject and changing original.innerObject.property will change clone.innerObject.property.
  • yes, this is a shallow clone. if you want a deep clone you must use JSON.parse(JSON.stringify(input))
  • /!\ JSON.parse(JSON.stringify(input)) messes up dates, undefined, ... It is not the silver bullet for cloning! See: maxpou.fr/immutability-js-without-library
  • So is the hack JSON.stringify()/JSON.parse() really the recommended way to deep clone an object in ES6? I keep seeing it recommended. Disturbing.
  • @MarkShust JSON.parse(JSON.stringify(input)) will not work, because if there functions or infinity as values it will simply assign null in their place. It will only work if the values are simple are literals and not functions.
  • There is one, provided your object is a true object literal, and purely data, in which case JSON.parse(JSON.stringify(input)) is a proper deep clone. However, the moment prototypes, functions or circular references are in play, that solution no longer works.
  • @Mike'Pomax'Kamermans That's true. Losing functionality for getters and setters is terrible, though...
  • If you need a generic function to deep clone any object, check out stackoverflow.com/a/13333781/560114.