How to create a new instance of an object in a javascript array and modify its variables without modifying the object of the first one

0

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;
}
    
asked by Israel Perales 11.02.2017 в 01:51
source

2 answers

0

It would be converted to JSON in the following way ....

var objectos2 = JSON.parse( JSON.stringify( objetos1 ) ); 
objectos2[ 'nombre' ] = "enrique"; 
console.log( objectos1[ 'name' ] ); // israel
console.log( objectos2[ 'name' ] ); // enrique

link

    
answered by 11.02.2017 / 02:03
source
0

You can use Object#create :

var o = {nombre : 'israel'};
var o2 = Object.create(o);

o2.nombre = 'Perico';
console.log(o, o2);
    
answered by 11.02.2017 в 12:30