0

I'm trying to copy an attribute to a new object and then delete the attribute from the original object. This is for a Redux Reducer I'm trying to flatten. This is not the same question as above. Cloning helps but both are still being deleted in the reducer.

i.e. parent{child} to {parent, child}

function mergeAndDelete(state, type, id, ent, attrib) {
 const clone = { ...ent[attrib] };
 merge(state, type, id, clone);
 delete ent[attrib];
}

I thought the spread operator would make a new copy of the object?

Both the clone and the original are getting deleted in this method.

beek
  • 3,522
  • 8
  • 33
  • 86
  • You'll need to provide some usage details – pilchard Apr 13 '22 at 22:05
  • 2
    You are doing shallow copy instead of deep copy see link below https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – miyav miyav Apr 13 '22 at 22:05
  • 1
    You can use map for that https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?retiredLocale=nl – Grumpy Apr 13 '22 at 22:06
  • 1
    I can't reproduce your problem. You're spreading the value at `ent[attrib]` but deleting a reference to that value in the original object with your `delete` so it shouldn't affect the clone (even as a shallow copy). [fiddle](https://jsfiddle.net/2v8gcn7t/) – pilchard Apr 13 '22 at 22:19
  • Yea actually I'm getting the same thing. It's in a redux reducer I'm trying to flatten. Even with a deepClone the entity gets deleted after being cloned. – beek Apr 13 '22 at 22:21
  • You should probably avoid mutating the passed `ent` anyway as it's a sideeffect that is very hard to debug... – pilchard Apr 13 '22 at 22:23
  • This is not the same question please can whoever did that remove it! It's a totally different questions! – beek Apr 13 '22 at 22:23
  • The problem is you indicated that a deep clone had resolved your issue.. but I agree there is something else at work, but you'll need to post more details for further help as there's nothing in your code that would result in the effect you're describing. [voted to reopen] – pilchard Apr 13 '22 at 22:27
  • Use `window.structuredClone()`. – connexo Apr 13 '22 at 23:13
  • @connexo it's not a deep clone issue (and that is covered in the first answer of the flagged duplicate) – pilchard Apr 14 '22 at 09:49

0 Answers0