'Deleting a property from a clone deletes it from the original as well. ReactJS

I have an object that contains data I read from a file (called it data). I cloned a property from it (called images) to another object (called tempixy ) and deleted a property (called src) from each element within the clone, but for some reason the property got deleted from the original object as well.
I tried cloning the object with Object.assign({}, data.images) as well but it still wont work.
I know can access the event directly but I prefer not to.

function openFile(evt) {

      const fileReader = new FileReader();
      fileReader.readAsText(evt.target.files[0], "UTF-8");
      fileReader.onload = e => {
        let data=JSON.parse(e.target.result)
        let tempixy ={...data.images};
        Object.keys(tempixy).map(function (key, index) {
          delete tempixy[key].src
        });
        console.log(data.images) //->prints it without the src property
        
      };
     
      evt.target.value = null;
  }


Solution 1:[1]

The spread operator (...) will perform a shallow clone, e.g. supose you're trying to do

const obj = {
  some: 'property',
  another: {
    deep: 'property',
  },
};

const clone = { ...obj };

The spread operator will take the keys some and another and will put them with their respective values into the new object. Notice the deep key will not be cloned, so if you change clone.another.deep, this will reflect to obj.another.deep.

What you'd have to do then is

const deepClone = {
  ...obj,
  another: {
    ...obj.another
  },
};

And repeat it for all levels of nesting your object have, which is an obnoxious task though. Luckily, there's the cloneDeep method from lodash which does exactly this.

import cloneDeep from 'lodash.clonedeep';

const deepClone = cloneDeep(obj);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Diego Fidalgo