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
data = { question_11_address: "124 Aspen Rd", question_12_city: "South Orange", question_13_state: "NJ", question_14_zip: "07052", question_15_country: "USA", question_11_address_copy_0: "123 Main St", question_12_city_copy_0: "Jersey City", question_13_state_copy_0: "NJ", question_14_zip_copy_0: "07302", question_15_country_copy_0: "USA", question_11_address_copy_1: "110 Marrin St", question_12_city_copy_1: "Hoboken", question_13_state_copy_1: "NJ", question_14_zip_copy_1: "07302", question_15_country_copy_1: "USA", }
transform to …
const finalAddresses = [ { address: "124 Aspen Rd", city: "South Orange", state: "NJ", zip: "07052", country: "USA", }, { address: "123 Main St", city: "Jersey City", state: "NJ", zip: "07302", country: "USA", } { address: "110 Marrin St", city: "Hoboken", state: "NJ", zip: "07302", country: "USA", }, ];
Instead what I’m getting is …
const finalAddresses = [ { address: "124 Aspen Rd", city: "South Orange", state: "NJ", zip: "07052", country: "USA", }, { address: "110 Marrin St", city: "Hoboken", state: "NJ", zip: "07302", country: "USA", }, { address: "110 Marrin St", city: "Hoboken", state: "NJ", zip: "07302", country: "USA", }, ];
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:
const addressObject = {}; const addressCounterArray = ... // [0,1]; const addressCopyArray = addressCounterArray.map((index) => { return generateCorrectAddressFormat(index, addressObject, sectionAddress); });
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:
const addressCopyArray = addressCounterArray.map((index) => { return generateCorrectAddressFormat(index, {}, sectionAddress); });