How to change object values without assigning it to another object
You have two variables, one referencing the other one like this:
var person = { name: "John" };
var luckyWinner = person;
Now, say want to get some data from an AJAX call and assign it to person, but you also want luckyWinner
to keep the reference:
// say we received updatedPerson = { name: "Jonathan" } from the ajax call
console.log(person); // { name: "John" }
person = updatedPerson;
console.log(person); // { name: "Johnathan" }
console.log(luckyWinner); // { name: "John" }
How can you make the luckyWinner
always reflect the value of person
?
Of course, you could copy the properties one by one from updatedPerson
with a loop, but is there a better way?
Next time you run into this kind of situation, try storing the value in a subproperty, like this:
var person = { data: { name: "John" }};
var luckyWinner = person;
// then, after the ajax call
console.log(person.data); // { name: "John" }
person.data = updatedPerson;
onsole.log(person.data); // { name: "Johnathan" }
console.log(luckyWinner.data); // { name: "Johnathan" }
This way, the reference to person
will always be up to date!
Comments ()