How to save an object (JSON) per copy in Javascript

1

How to store the current state of a json object per copy? Because if I save by reference I lose the exact information of the object at that moment of the assignment. Example object:

var sessao = {"num":"1"};  var vetorSessoes = [];

function salvando(){
  var copia = sessao; 
  var vetorSessoes.push(copia);
  sessao.num = 2;
}

function teste(){
  console.log(vetorSessoes[0]); //deveria printar '1' ao invés de '2'
}

For vectors, I have learned to use .slice() , how do I make this copy with objects and specifically json.

    
asked by anonymous 17.02.2018 / 02:05

2 answers

3

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);
    
17.02.2018 / 02:26
0

You did not include in the sessao the value of num if you just want to include the value in the array, which is what it looks like at the beginning vetorSessoes[0] :

var copia = sessao.num;

var sessao = {"num":"1"};
var vetorSessoes = [];

function salvando(){
  var copia = sessao.num; 
  vetorSessoes.push(copia);
  sessao.num = 2;
  teste();
}

function teste(){
  console.log(vetorSessoes[0]); //deveria printar '1' ao invés de '2'
}
<button type="button" onclick="salvando()">Salvar</button>

Or you can add the object to the array as JSON:

var sessao = {"num":"1"};
var vetorSessoes = [];

function salvando(){
  var copia = JSON.stringify(sessao);
  vetorSessoes.push(copia);
  sessao.num = 2;
  teste();
}

function teste(){
  console.log(JSON.parse(vetorSessoes[0]).num); //deveria printar '1' ao invés de '2'
}
<button type="button" onclick="salvando()">Salvar</button>
    
17.02.2018 / 02:18