Created
November 26, 2011 18:22
-
-
Save NV/1396086 to your computer and use it in GitHub Desktop.
Clone an Object with all its circular references. Take that jQuery.extend!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cloneObject(object) { | |
return extendObject({}, object); | |
} | |
function extendObject(base, object) { | |
var visited = [object]; | |
// http://en.wikipedia.org/wiki/Adjacency_list_model | |
var set = [{value: base}]; | |
_extend(base, object); | |
return base; | |
function _extend(base, object) { | |
for (var key in object) { | |
var value = object[key]; | |
if (typeof value === 'object') { | |
var index = visited.indexOf(value); | |
if (index === -1) { | |
visited.push(value); | |
var newBase = base[key] = {}; | |
set.push({up: base, value: newBase}); | |
_extend(newBase, value); | |
} else { | |
base[key] = set[index].value; | |
} | |
} else { | |
base[key] = value; | |
} | |
} | |
} | |
} | |
// Example #1 | |
var a = {}; | |
a.self = a; | |
console.log(a, cloneObject(a)); | |
// Example #2 | |
var b = { | |
x: 1, | |
y: { | |
y1: 2, | |
z1: { | |
z2: 3 | |
} | |
} | |
}; | |
b.top = b; | |
b.y.top = b; | |
b.y.z1.top = b; | |
b.y.up = b; | |
b.y.z1.up = b.y; | |
b.y.z1.self = b.y.z1; | |
var bClone = cloneObject(b); | |
bClone.x = 42; | |
bClone.y.y1 = 13; | |
console.log(b, bClone); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In ES6, with array support