I am needing to clone an object in JavaScript, at the moment for simple objects that only contain only attributes I am doing it in the following way using JSON.stringify()
and JSON.parse()
:
let original = { nombre: 'juan', apellido: 'peres', edad: 23 }
let copia = JSON.parse(JSON.stringify(original));
I don't think it's the most optimal (that's why the question) but it works, the doubt is, how to clone any object that contains methods or internal functions defined for example.
You can use Object.assign(target, ...sources) , but this is as of ECMAScript 2015 .
Here is a very good article about cloning:
With jQuery you can use the extend function.
var copy = jQuery.extend(true, {}, original);
Here I leave the link for you to find out better. https://api.jquery.com/jquery.extend/
There is a very easy way to clone an object with the static assign method of Object
link js documentation mozilla developer network