Deep Copy
by Hari Menon
JavaScript
var deepCopy = function (obj) {
var copy = {};
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i], value = obj[keys[i]];
copy[key] = value instanceof Object && !(value instanceof Array) ? deepCopy(value) : value;
}
return copy;
};
var testObject = [{
'country': 'US',
continent: 'North America',
isNorthernHemisphere: true,
states: {
count: 50,
names: [
'AL',
'AK',
'AZ',
'AR'
],
hasBackend: null, // supports null
dummy: undefined
}
}, {
'country': 'UK',
continent: 'Europe',
isNorthernHemisphere: true,
states: {
count: 6,
names: [
'A',
'B',
'C',
'D'
],
hasBackend: null, // supports null
dummy: undefined
}
}];
console.log(deepCopy(testObject));