tags:

views:

75

answers:

3

How to clone js object with out reference like these:

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

Any ideas?

A: 
function objToClone(obj){
  return (new Function("return " + obj))
}
Floyd
Ew, eval()! Not sure this would work either, unless obj has a meaningful toString() method.
thomasrutter
+2  A: 

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?

thomasrutter
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
+1  A: 

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 (typeof obj[i] == 'object') {
            clone.i = cloneObj(obj[i]);
        } else {
            clone.i = obj[i];
        }
    }

    return clone;
}
BoltClock
`obj.i` will not work, you will access to the `"i"` property literally, you need to use the bracket notation, e.g. `obj[i]`
CMS
@CMS: thanks, I've fixed it now.
BoltClock