Is there a more elegant solution for restructuring this code, especially considering the only variation is in the key name of a return object?
function generateContactInput(rawData, contactId) {
const data = rawData
? rawData.replace(/["]+/g, '').split(SEMICOLON)
: undefined;
const populatedData = data
? data.map((value) => ({ contactId, value }))
: undefined;
if (Array.isArray(populatedData) && populatedData.length > 0)
populatedData[0].isPrimary = true;
return populatedData;
}
function generateContactAddressInput(rawAddresses, contactId) {
const data = rawAddresses
? rawAddresses.replace(/["]+/g, '').split(SEMICOLON)
: undefined;
const populatedData = data
? data.map((streetAddress) => ({ contactId, streetAddress }))
: undefined;
if (Array.isArray(populatedData) && populatedData.length > 0)
populatedData[0].isPrimary = true;
return populatedData;
}
The distinguishing line is:
? data.map((streetAddress) => ({ contactId, streetAddress }))