Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.forEach() and Array.slice() together doesn't work correctly [duplicate]

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);
like image 425
Víctor Manuel Monsalve Retamal Avatar asked Jan 05 '23 22:01

Víctor Manuel Monsalve Retamal


2 Answers

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;
}
like image 67
hsh Avatar answered Jan 08 '23 12:01

hsh


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

like image 36
Nick Tomlin Avatar answered Jan 08 '23 11:01

Nick Tomlin