Array.forEach () and Array.slice () work together incorrectly

it should Array.slice()allow me to make a copy of the array, and then I can change this copy without changing the original array, but when I use Array.forEach()the copy to delete some values, these values ​​are also removed from the original array. Does anyone have an idea why this is happening? Here is the code I 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);
+4
source share
2 answers

In accordance with this definition . The slice () method returns a shallow copy of part of the array into a new array object.

- - . , . - , , .. .

javascript :

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;
}
+5

Slice , ( ).

- Lodash cloneDeep

+4

All Articles