for array of objects of 1 level best to use
https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript
clonedArray = nodesArray.map(a => {return {...a}})
For multiple depthbest to use
let clonedArray = JSON.parse(JSON.stringify(nodesArray))
note: do not use JSON.pares(..JSON.stringify) for 1 level as JSON.stringify will return {} for some cases :https://medium.com/@pmzubar/why-json-parse-json-stringify-is-a-bad-practice-to-clone-an-object-in-javascript-b28ac5e36521
JSON.stringify({ key: undefined });
JSON.stringify({ key: Symbol() });
JSON.stringify({ key: function(){} });// all will be converted to just "{}"
deep clone function :
https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascriptfunction deepClone (item) {
if (Array.isArray(item)) {
var newArr = [];
for (var i = item.length; i-- > 0;) {
newArr[i] = deepClone(item[i]);
}
return newArr;
}
if (typeof item === 'function' && !(/\(\) \{ \[native/).test(item.toString())) {
var obj;
eval('obj = '+ item.toString());
for (var k in item) {
obj[k] = deepClone(item[k]);
}
return obj;
}
if (item && typeof item === 'object') {
var obj = {};
for (var k in item) {
obj[k] = deepClone(item[k]);
}
return obj;
}
return item;
}
No comments:
Post a Comment