-1

I have to clone an array with some objects inside. I tried "JSON.parse(JSON.stringify)" and thirdParty Plugin Lodash, but both are return a empty result. Do i have the wrong data to clone ?

The Function looks so:

currentObject: any[];
addPropertiesToDisplay() {
console.log(this.analyseFacade.householdService.currentObject);
this.currentObject = _cloneDeep(this.analyseFacade.householdService.currentObject);
console.log(this.currentObject);

}

the console.log shows this

enter image description here

Woogielicious
  • 174
  • 2
  • 12
  • You may be missing the dot after your underscore. Try: this.currentObject = _.cloneDeep(this.analyseFacade.householdService.currentObject); – Max K Nov 04 '20 at 11:45
  • hmm i get an error if i try this. I think this was an older version import from lodash. I imported it like "import { cloneDeep as _cloneDeep } from 'lodash';" and installed "lodash-es" and "@types/lodash-es" – Woogielicious Nov 04 '20 at 12:17
  • 1
    Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Heretic Monkey Nov 04 '20 at 16:15

1 Answers1

-1

I fixed it by writing a empty Object to the stringify. This should also work for Lodash. But in this case i dont use a third party plugin.

this.currentObject = JSON.parse(
  JSON.stringify(Object.assign({}, this.analyseFacade.householdService.currentObject))
);
Woogielicious
  • 174
  • 2
  • 12
  • This makes a shallow clone of `this.analyseFacade.householdService.currentObject`. See [MDN's warning about `Object.assign` doing a shallow clone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Deep_Clone). – Heretic Monkey Nov 04 '20 at 16:25
  • Yes u are right, i know this and i know i have to fix the Service where the data came from to clone it here in a correct way. – Woogielicious Nov 05 '20 at 07:59