-1

I have two objects like:

var a = { a1: 'a1', a2: 'a2', a3: {}}
var b = { a1: 'b1', a2: 'b2', a3: {}}

How i can assign values to the properties of one object to another?

If i try use a=b As I get an object a link to b. I just want to equate the value of the properties.

Buboon
  • 405
  • 5
  • 15
  • Are you trying to create a copy? – thefourtheye Oct 25 '15 at 14:59
  • "Equate" how exactly? Do you just want to overwrite `b` with a clone of the object in `a` ? – adeneo Oct 25 '15 at 14:59
  • Sounds like you're trying to copy the object. See this: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object – Cliff Ribaudo Oct 25 '15 at 14:59
  • Possible duplicate of [What is the most efficient way to clone an object?](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object) – Cliff Ribaudo Oct 25 '15 at 15:00
  • Possible duplicate of [How to duplicate object properties in another object?](http://stackoverflow.com/questions/9362716/how-to-duplicate-object-properties-in-another-object) – Matt Browne Oct 25 '15 at 15:08

2 Answers2

2

Use Object.assign().

Object.assign(b, a); // Assign all properties of a to b. Changing b in the process.

Be advised: Object.assign() it relatively new, and is not supported in Internet Explorer as of yet.

A polyfill for it is available here.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
0

There are lot's of way to clone an object.

The two elegant (may not be the most efficient) ways are:

Without JQUERY - Using the serialize\deserialize way

var obj = { a1: 'a1', a2: 'a2', a3: {}}
var cloned = JSON.parse(JSON.stringify(obj));

With JQUERY - Using $.extend:

var obj = { a1: 'a1', a2: 'a2', a3: {}}
var cloned = $.extend({}, obj);
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99