25

Possible Duplicate:
What is the most efficient way to clone a JavaScript object?

How to clone js object with out reference like these:

{ ID: _docEl,
  Index: next,
  DocName: _el
}

Any ideas?

Community
  • 1
  • 1
Harold Sota
  • 7,290
  • 12
  • 55
  • 83

5 Answers5

11

You'll have to iterate over the object and make copies of all its properties.

And then if any of its properties are also objects, assuming you want to clone those too, you'll have to recurse into them.

There's various methods for doing this here: What is the most efficient way to clone a JavaScript object?

Community
  • 1
  • 1
thomasrutter
  • 109,718
  • 27
  • 142
  • 163
  • 1
    Note too that this isn't one-size-fits-all - this is unlikely to do anything useful for built-in objects like DOM nodes where you'd want to use cloneNode() method, etc. – thomasrutter Aug 13 '10 at 07:35
6

Here's how I'd do it, based on thomasrutter's suggestion (untested code):

function cloneObj(obj) {
    var clone = {};

    for (var i in obj) {
        if (obj[i] && typeof obj[i] == 'object') {
            clone[i] = cloneObj(obj[i]);
        } else {
            clone[i] = obj[i];
        }
    }

    return clone;
}
Community
  • 1
  • 1
BoltClock
  • 665,005
  • 155
  • 1,345
  • 1,328
5

You can use jQuery.extend:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

The following post is so helpful:

What is the most efficient way to deep clone an object in JavaScript?

Community
  • 1
  • 1
Mahmood Dehghan
  • 7,021
  • 4
  • 55
  • 68
2

JavaScript JS object clone

Object._clone = function(obj) {
  var clone, property, value;
  if (!obj || typeof obj !== 'object') {
    return obj;
  }
  clone = typeof obj.pop === 'function' ? [] : {};
  clone.__proto__ = obj.__proto__;
  for (property in obj) {
    if (obj.hasOwnProperty(property)) {
      value = obj.property;
      if (value && typeof value === 'object') {
        clone[property] = Object._clone(value);
      } else {
        clone[property] = obj[property];
      }
    }
  }
  return clone;
};

CoffeeScript JS object clone

# Object clone
Object._clone = (obj) ->
  return obj if not obj or typeof(obj) isnt 'object'
  clone = if typeof(obj.pop) is 'function' then [] else {}

  # deprecated, but need for instanceof method
  clone.__proto__ = obj.__proto__

  for property of obj
    if obj.hasOwnProperty property
      # clone properties
      value = obj.property
      if value and typeof(value) is 'object'
        clone[property] = Object._clone(value)
      else
        clone[property] = obj[property]

  clone

Now you can try to do that

A = new TestKlass
B = Object._clone(A)
B instanceof TestKlass => true
the-teacher
  • 579
  • 8
  • 19
1
function objToClone(obj){
  return (new Function("return " + obj))
}
Floyd
  • 1,888
  • 12
  • 19