For a simple copy ( shallow ) of an object you can use Object.assign
:
var copia = Object.assign({}, sessao);
See how you get the results you expect:
var sessao = {"num":"1"};
var vetorSessoes = [];
function salvando(){
var copia = Object.assign({}, sessao);
vetorSessoes.push(copia);
sessao.num = 2;
}
function teste(){
console.log("Copia tem ", vetorSessoes[0]); //deveria printar '1' ao invés de '2'
}
salvando();
teste();
console.log("Sessão tem ", sessao);
However this will not work correctly if you have objects within objects, such as:
var sessao = {
"num":"1",
"casa": {
"area": 110,
"divisoes": 5
}
};
In this case you have to make a deep copy ( deep ), which you can do using JSON.parse
and JSON.stringify
:
var copia = JSON.parse(JSON.stringify(sessao));
Example also from this version:
var sessao = {
"num":"1",
"casa": {
"area": 110,
"divisoes": 5
}
};
var vetorSessoes = [];
function salvando(){
var copia = JSON.parse(JSON.stringify(sessao));
vetorSessoes.push(copia);
sessao.num = 2;
sessao.casa.area = 90;
sessao.casa.divisoes = 3;
}
function teste(){
console.log("Copia tem ", vetorSessoes[0]); //deveria printar '1' ao invés de '2'
}
salvando();
teste();
console.log("Sessão tem ", sessao);