0

I'm making an HTTP request to my backend and I receive a JSON from the server, so with the response I set my dataSource like so:

  await this.apisService.getList(_token).then((data) => {
  this.arrList = data;
  this.arrListHelper = data; ...

And if I'm changing something in the arrList, the helper is changing as well, so I made a test function to check different methods I found online and only the JSON parse thing solved my problem. I get why is this is happening I just don't get why these solutions doesn't work:

const _aaa = this.arrList.slice();
const _bbb = Object.create(_aaa);
const _ccc = Array.from(_bbb);
const _ddd = { ..._ccc };
const _eee = Object.assign({}, _ddd);
const _fff = JSON.parse(JSON.stringify(_eee));

this.arrList [0]['Name'] = 'ASD';
console.log(_aaa[0]); // ASD
console.log(_bbb[0]); // ASD
console.log(_ccc[0]); // ASD
console.log(_ddd[0]); // ASD
console.log(_eee[0]); // ASD
console.log(_fff[0]); // original
K. Anye
  • 158
  • 3
  • 16
  • All of those methods save JSON.parse/JSON.stringify create shallow copies (except `Object.create`, which doesn't even do that) – CertainPerformance Sep 04 '19 at 08:37
  • 1
    All you're doing is creating new arrays. However, the objects inside are not newly created. This is what's meant with a shallow clone/copy. `JSON.parse(JSON.stringify(..))` is one way of doing a deep clone. Another popular one is using [lodash's cloneDeep](https://lodash.com/docs/4.17.15#cloneDeep) – Geert-Jan Sep 04 '19 at 08:51

0 Answers0