1

Okay, I'm rewriting this because people kept misinterpreting it.

Given two objects x and y, I wish to replace all properties of x with that of y.

(Note that this is not regular cloning as that implies creating a new object (z). Object x is to be updated, not replaced.)

My idea is that one could do this by using two for-in loops (with hasOwnProperty checks), one for removing everything from x and one for copying everything from y to x, but that feels like an ugly solution somehow.

Is there some more elegant way to do this? Does JavaScript (or possibly jQuery) have some built-in function for copying the state of one object into another object that already exists?

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
  • See this - http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object – web-nomad Nov 27 '13 at 13:15
  • @Pushpesh: I'm not talking about creating a new object that is a clone, I'm talking about turning an **existing object** into a clone. – BambooleanLogic Nov 27 '13 at 13:16
  • Also check out the [Prototype](http://sourcemaking.com/design_patterns/prototype) design pattern. – Dan Nov 27 '13 at 13:17
  • You are probably looking for elegant ways to do a **mixin**, so searching for that word in conjunction with Javascript might help. – Geeky Guy Nov 27 '13 at 13:30
  • @Andy: The details about that are irrelevant to the central question. The point is that all the data in object `x` needs to be replaced with the data in object `x2`, *as opposed to* using a `.clone()` method on `x2` to create an object `x3`. – BambooleanLogic Nov 27 '13 at 13:35

1 Answers1

1

I think jQuery.extend() is what you are looking for.

lex82
  • 11,173
  • 2
  • 44
  • 69
  • Hm, it appears to do 2/3 of what I need. (It adds and replaces but, for obvious reasons considering what its intended use is, doesn't remove.) Even then, I think I can live with manually clearing `x` before calling this. :) – BambooleanLogic Nov 27 '13 at 14:31