0

I have the following code:

let myObj = {
    val1: "Cookies",
    val2: 15
};

let myObj2 = myObj;

myObj2.val1 = "Cake";

console.log(myObj.val1);// This logs "Cake"

I want "Cookies" to be output instead of "Cake", what's the easiest way to make that happen?

OOPS Studio
  • 732
  • 1
  • 8
  • 25

1 Answers1

0

There are a couple ways to do this, but my personal favorite is by using the Object.assign() method.

The best way to do this for your case would be:

let myObj = {
    val1: "Cookies",
    val2: 15
};

let myObj2 = Object.assign({},myObj);

myObj2.val1 = "Cake";

console.log(myObj.val1);// This logs "Cookies"
console.log(myObj.val2);// This logs "Cake"

The Object.assign() method is a static method of the class Object. It takes two parameters. It takes in an object to write to, and an object to read from. It then assigns all the data inside the read-object to the write-object, and it also returns the result. This is important, as it allows us to use it in this way. If it didn't return the result, our code would have to look like this:

let myObj = {
    val1: "Cookies",
    val2: 15
};

let myObj2 = {};

Object.assign(myObj2,myObj);

myObj2.val1 = "Cake";

console.log(myObj.val1);// This logs "Cookies"
console.log(myObj.val2);// This logs "Cake"

but since Object.assign() returns the value that it assigns to the write-object, we can simply pass in an empty object and assign the returned value to a variable (Or output it to the console, pass it to a function, or really anything we want) like so:

var copy = Object.assign({},original);// Will return the value assigned to the empty object and
// store it inside "copy"

One thing to keep in mind is that this only makes a non-deep copy of the object! If you have an object inside your object, then that object will be passed my reference, which is exactly what you don't want. But as long as your object doesn't contain any other objects, then this should work perfectly! (If your object does contain other objects, then you'll need to use one of the methods found here: JavaScript: How to pass object by value?)

Dharman
  • 30,962
  • 25
  • 85
  • 135
OOPS Studio
  • 732
  • 1
  • 8
  • 25