For a single copy (Shallow) of an object can use Object.assign
:
var copia = Object.assign({}, sessao);
See how it already gives the result 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 properly if you have objects inside objects, for example:
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 of 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);
It is important to understand that in this example,
sessao
is not a JSON. He is a object. JSON is a data representation that uses the Javascript object format.– Pablo Almeida