I was trying to copy/clone the object and edit the new one but whenever I change edit NewObject, olderObject also get's changed, suppose here is my Object
var OriginalObject= {
"some": 2,
"thing": [2, 3, 4, 5],
"other": {
"mymy": [60],
"2": "asdfgret"
};
How do I clone it, to edit and do the required changes, without affecting OriginalObject data?
I was copying it like
var new_object= OriginalObject;
But it doesn't work.Any helpful link or code will work, thanks
You can directly copy a new object using assign in javascript like below
var Cloned_new_object = Object.assign({}, OriginalObject);
// The "Cloned_new_object" variable now consists of all "Original_object" keys and values.
// Both variables are independent. Either one can be edited.
Or you can create own function like below
function CopyObjectFunction(a) {
// "use strict";
// Un-comment the "use strict" directive statement if
// this function is placed outside your own function.
var result = {};
var buff = [];
var l;
if (a.constructor === Object) { // check if the input is an Object type.
buff = Object.keys(a); // get all keys of the input Object.
l = buff.length; // the length of the keys (array now).
if (l > 0) { // if the keys length greater than 0 (there's key found).
buff.forEach(function (v) {
result[v] = a[v];
});
}
}
// the result.
// if the input is an empty object, then the procedure above will be skipped.
return result;
}
and use it like below
var new_cloned_object = CopyObjectFunction(OriginalObject);
That's it, you are done.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly