Skip to content
Advertisement

How can I map over an object and set it to another object without overwriting the previous values?

I’m working with a form that has sections where there can be multiple addresses, ids, etc. I’m taking the value of those objects and mapping it to another object that my API can understand. The problem I’m having is that when I have more than two addresses or ids my function overwrites all the additional ones with the last one that I pass.

For instance, I expect to take this data

JavaScript

transform to …

JavaScript

Instead what I’m getting is …

JavaScript

Clearly I’m overwriting the object that I’m passing to my function with the last value, however I’m not sure how to fix it. I’ve tried many approaches, including pushing the object to my array before calling my function again, but I’m still having this problem. Please see my codesandbox for the full code.

Advertisement

Answer

You pass the same object to your “generate” function twice by reference:

JavaScript

Therefore, you don’t have two objects – it’s the very same object, included in the resulting array twice, and with the values corresponding to the last index that you “generated” it with. You can verify this by running console.log(finalAddresses[1] === finalAddresses[2]). === checks for equality by reference, so it will only log true when it is literally the same object, not just two objects with the same values.

Instead, you should actually use a new object each time, for example by doing:

JavaScript
Advertisement