How to work with Javascript objects?

Asked

Viewed 63 times

0

I have two objects, objeto1 and objeto2 and I want to assign all the values of objeto1 at the objeto2, but when I use objeto2 = objeto1 and change some value of objeto2 the objeto1 is also changed because they have the same address. How to create a new object with the same values quickly?

  • A simple option - but not very efficient - is to serialize and de-serialize this object using JSON: objeto2 = JSON.parse(JSON.stringify(objeto1)); Note: only works if your object has no cycles.

1 answer

0

var objeto1 = new Object();
var objeto2 = new Object();

// objeto1 = objeto2 funciona como apontamento
// quando é nova instancia de objeto então tem que instanciar e não referenciar

Case of cloning already completed object:

    function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

var d1 = new Date();

/* Wait for 5 seconds. */
var start = (new Date()).getTime();
while ((new Date()).getTime() - start < 5000);


var d2 = clone(d1);
alert("d1 = " + d1.toString() + "\nd2 = " + d2.toString());

https://stackoverflow.com/a/728694/3130590

  • Yes Snneps thank you very much for your reply, but the objeto1 is already instantiated and filled, and I would like to duplicate it to objeto2 independently.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.