1 min read

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(;		// { name: "John" } = updatedPerson;
onsole.log(;		// { name: "Johnathan" }
console.log(;	// { name: "Johnathan" }

This way, the reference to person will always be up to date!

Clear, straight to the point tutorials, straight to your inbox

Enter your email below to receive new articles as soon as they are published!