How to clone js object?

17,402

Solution 1

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?

Solution 2

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;
}

Solution 3

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?

Solution 4

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

Solution 5

function objToClone(obj){
  return (new Function("return " + obj))
}
Share:
17,402

Related videos on Youtube

Harold Sota
Author by

Harold Sota

I have ten years’ experience in software development and consultancy. Covering fully the software development lifecycle, worked in teams of various sizes and in the last four years had the opportunity to lead the team and successfully implemented numerous technologies in various projects.

Updated on April 30, 2022

Comments

  • Harold Sota
    Harold Sota almost 2 years

    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?

  • thomasrutter
    thomasrutter over 13 years
    Ew, eval()! Not sure this would work either, unless obj has a meaningful toString() method.
  • Christian C. Salvadó
    Christian C. Salvadó over 13 years
    obj.i will not work, you will access to the "i" property literally, you need to use the bracket notation, e.g. obj[i]
  • thomasrutter
    thomasrutter over 13 years
    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.
  • BoltClock
    BoltClock over 13 years
    @CMS: thanks, I've fixed it now.
  • Niyaz
    Niyaz about 11 years
    This does not seem right. cloneObject({ name: null }) => {"name":{}}
  • BoltClock
    BoltClock about 11 years
    @Niyaz: Thanks, I added a fix.
  • borrel
    borrel over 10 years
    would that not return a reference?