47

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?

Mubashar Abbas
  • 5,536
  • 4
  • 38
  • 49
  • 2
    Make a copy of the object - one simple way is: `var vegetable = JSON.parse(JSON.stringify(fruit));` – tymeJV Oct 19 '16 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. – Liam Oct 19 '16 at 14:03
  • Check this SO question out: http://stackoverflow.com/questions/12690107/clone-object-without-reference-javascript – Koen Oct 19 '16 at 14:04

1 Answers1

62

You can use Object.assign:

var fruit = {
   name: "Apple"
};

var vegetable = Object.assign({}, fruit);
vegetable.name = "potatoe";
console.log(fruit);
BrTkCa
  • 4,703
  • 3
  • 24
  • 45
  • 1
    Note, this doesn't assign the value (as the OP wants) but copies it into a new object. Subtle but sometimes important distinction – Liam Oct 19 '16 at 14:04
  • 1
    can you please explain a little this `assign` call? what is that empty object in the first argument? – Mubashar Abbas Oct 19 '16 at 14:05
  • 2
    @MubasharAbbas [See here](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) – Liam Oct 19 '16 at 14:16
  • Object.assign({}, obj); you can see more in: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/assign – Rafael Andrs Cspedes Basterio Dec 05 '17 at 21:09