The problem is the following one I have a global arrangement with a list of objects and I want to make temporary modifications to an element of the list and I want the modifications in the element to be temporary, that is, if I access this element of the list should be as I left it at the beginning.
These are the attempts I've made
Attempt 1:
var objetos1 = [{nombre : 'israel'}];
var objeto = new Object( objetos1[0] );
var objetos2 = [objeto];
objetos2[0].nombre = 'enrique';
console.debug(objetos1[0].nombre);//Espero que diga israel
console.debug(objetos2[0].nombre);//Espero que diga enrique
Attempt 2:
var objetos1 = [{nombre : 'israel'}];
var objetos2 = new Array();
objetos2.push( new Object( objetos1[0] ) )
objetos2[0].nombre = 'enrique';
console.debug(objetos1[0].nombre);//Espero que diga israel
console.debug(objetos2[0].nombre);//Espero que diga enrique
In the 2 attempts the result is the same, if I modify the object of the first or the second arrangement they will be modified in the 2, therefore it will always say enrique
.
I am trying to avoid having to assign all the properties to a new variable because when there are few properties the code is small and it works but since there are many properties, I would have to create a mapping function and it is not the option that I want.
It is possible to lose the reference to the object with a function that creates a copy of it, which I made generic, but I hope to find a better solution.
/**
* Copia las propiedades principales
* de un objeto a otro.
* @param objetoOriginal Objeto original con las propiedaes a copiar.
* @param objetoCopia Objeto al que se le copiaran las propiedades.
* @return objeto copia con las propiedades del objeto original.
* @author Jesus Perales.
*/
function copiarValoresObjeto(objetoOriginal, objetoCopia){
for (var prop in objetoOriginal) {
if (objetoOriginal.hasOwnProperty(prop)) {
objetoCopia[prop] = objetoOriginal[prop];
}
}
return objetoCopia;
}