it's supposed to Array.slice()
let me to make a copy of an array, and then I can modify that copy without modifying the original array, but when I use Array.forEach()
over the copy for delete some values this values also are removed from the original array. Does anybody have an idea why this happens?
Here is the code that I've used:
var originalArray = [
{ id: 1, name: 'Sales', datasources: [
{ id:1 , name: 'datasource1', fields: [] },
{ id:2 , name: 'datasource2', fields: [] },
] },
{ id: 4, name: 'Accounts', datasources: [
{ id:3 , name: 'datasource3', fields: [] },
{ id:4 , name: 'datasource4', fields: [] },
] },
{ id: 123, name: 'my datasources', datasources: [
{ id:1 , name: 'datasource1', fields: [] },
{ id:2 , name: 'datasource2', fields: [] },
{ id:3 , name: 'datasource3', fields: [] },
{ id:4 , name: 'datasource4', fields: [] },
] },
{ id: 12, name: 'shared datasources', datasources: [
{ id:13 , name: 'myshared datasource', fields: [] },
{ id:16 , name: 'hello test', fields: [] },
] },
];
var copyOfOriginalArray = originalArray.slice();
copyOfOriginalArray.forEach((folder, index) => {
folder.datasources = folder.datasources.filter((o) => { return o.name.trim().toLowerCase().includes('hello'); });
});
JSON.stringify(originalArray);
JSON.stringify(copyOfOriginalArray);
Acording to this definition. The slice() method returns a shallow copy of a portion of an array into a new array object.
Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.
for deep copying any object in javascript you can use this function:
function deepCopy(oldObj) {
var newObj = oldObj;
if (oldObj && typeof oldObj === 'object') {
newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
for (var i in oldObj) {
newObj[i] = deepCopy(oldObj[i]);
}
}
return newObj;
}
Slice will create a copy of the array itself, but it will not clone the objects in the array (those will still be references).
You will need to recursively clone your array and its contents or use something like Lodash's cloneDeep
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With