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!

Know you should be immutably updating state in React,
but not sure what the best way is?

Get a handy reference of the most common state update operations and anti-patterns to watch out for 🕵🏻‍♀️

Drop in your email below to get a printable PDF with the cheatsheet. I'll also let you know whenever I publish a new blog post.

React Immutable State Updates Cheatsheet