I was wondering how can I create a JSON (JS) object and then clone it.
Just do
var x = {} //some json object here
var y = JSON.parse(JSON.stringify(x)); //new json object here
This is an issue I have often met when parsing JSON and reusing it several times in the code. And you want to avoid re-parsing every time from the original JSON string, or going the serialize/parse
way which is the less efficient way.
So in these cases where you want to adjust the parsed object but still keep the original unchanged, use the following function in both server (NodeJs) or client javascript code. The jQuery clone
function is less efficient because they treat the cases for functions, regexp, etc. The function below, only treats the JSON supported types (null, undefined, number, string, array and object):
function cloneJSON(obj) {
// basic type deep copy
if (obj === null || obj === undefined || typeof obj !== 'object') {
return obj
}
// array deep copy
if (obj instanceof Array) {
var cloneA = [];
for (var i = 0; i < obj.length; ++i) {
cloneA[i] = cloneJSON(obj[i]);
}
return cloneA;
}
// object deep copy
var cloneO = {};
for (var i in obj) {
cloneO[i] = cloneJSON(obj[i]);
}
return cloneO;
}