48

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?

3
  • 2
    Make a copy of the object - one simple way is: var vegetable = JSON.parse(JSON.stringify(fruit)); Commented Oct 19, 2016 at 14:02
  • How can I assign the value not the reference of an object to another object?. You can't JavaScript doesn't work like that. Your only option is to copy the object as @tymeJV says. Commented Oct 19, 2016 at 14:03
  • Check this SO question out: stackoverflow.com/questions/12690107/… Commented Oct 19, 2016 at 14:04

1 Answer 1

63

You can use Object.assign:

var fruit = {
   name: "Apple"
};

var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);

Sign up to request clarification or add additional context in comments.

4 Comments

Note, this doesn't assign the value (as the OP wants) but copies it into a new object. Subtle but sometimes important distinction
can you please explain a little this assign call? what is that empty object in the first argument?
@MubasharAbbas See here
Object.assign({}, obj); you can see more in: developer.mozilla.org/es/docs/Web/JavaScript/Referencia/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.