Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone js object? [duplicate]

Tags:

javascript

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?

like image 235
Harold Sota Avatar asked Aug 13 '10 07:08

Harold Sota


People also ask

How do you deep copy an object?

Copy an Object With Object.assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

How many ways can you clone an object in JavaScript?

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.


3 Answers

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?

like image 91
thomasrutter Avatar answered Oct 22 '22 09:10

thomasrutter


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;
}
like image 27
BoltClock Avatar answered Oct 22 '22 09:10

BoltClock


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?

like image 5
Mahmood Dehghan Avatar answered Oct 22 '22 08:10

Mahmood Dehghan