Assign value not reference in javascript
You can use Object.assign:
var fruit = {
name: "Apple"
};
var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);
Mubashar Abbas
I have over 5 years of experience in building web applications. I have completed multiple projects successfully, of various sizes, while working in teams and some while working individually. I have worked mostly in PHP, and more specifically the Laravel framework. I am also fluent with building mobile applications in Ionic framework. I have also had to build some components of an application in Java Spring framework. I also keep on learning new skills, I subscribe to Laracasts, and have taken courses from some well known authors about new trends and make a habit of spending some time to learn something new every day. I have gotten pretty good at Ruby on Rails framework, JAVA Spring framework, TDD, Ionic and frontend frameworks React, AngularJS, VueJS by sticking to this habit.
Updated on July 09, 2022Comments
-
Mubashar Abbas almost 2 years
I am having a little problem assigning objects in javascript.
take a look at this sample code that reproduces my problem.
var fruit = { name: "Apple" }; var vegetable = fruit; vegetable.name = "potatoe"; console.log(fruit);
it logs
Object {name: "potatoe"}
How can I assign the value not the reference of an object to another object?
-
Liam over 7 yearsNote, this doesn't assign the value (as the OP wants) but copies it into a new object. Subtle but sometimes important distinction
-
Mubashar Abbas over 7 yearscan you please explain a little this
assign
call? what is that empty object in the first argument? -
Liam over 7 years@MubasharAbbas See here
-
Rafael Andrs Cspedes Basterio over 6 yearsObject.assign({}, obj); you can see more in: developer.mozilla.org/es/docs/Web/JavaScript/Referencia/…