I have been exploring a way to transform an array by extracting specific properties. After successfully retrieving my contacts from my phone, I am aiming to restructure the data in a more organized format. How can I iterate over Array In and generate Array Out by capturing the first email and phone number values if available? Provided below is a sample of a contacts array:
Array In
let arrayIn= [
{phoneNumbers:[
{ label: 'work', number: '+3476859087'},
{ label: 'mobile', number: '+4567893214'}
],
lookupKey:"12345",
company:"PHONE",firstName:"John",contactType:"person",name:"John Smith",id:"879",
emails:[
{email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e343136300d33372a361e39333f3732703d3133">[email protected]</a>'}
],
lastName:"Smith",
},
{phoneNumbers:[
{ label: 'mobile', number: '+3476859087'},
{ label: 'work', number: '+4567773214'}
],
lookupKey:"890744",
company:"PHONE",firstName:"Carl",name:"Carl Johnson",id:"879",
emails:[
{email:'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="096a636661677a666761496e64686065276a6664">[email protected]</a>'}
],
lastName:"Johnson",
}
]
The desired output would be as follows: Array out
[
{name: 'John Smith', phone: 3476859087, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="543e27393d203c143339353d387a373b39">[email protected]</a>'},
{name: 'Carl Johnson', phone: 3476859087, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ffcd5f0f7f1ecf0f1dff8f2fef6f3b1fcf0f2">[email protected]</a>'}
]
To achieve this result, I iterated over the array to build a contact list and then stored each one in the state as I selected it. For reference, you can find my snack here:
I'm not looking for someone to complete the snack for me, just for guidance on transforming the array from Array In to Array Out.
Effective Solution
let arrayOut = arrayIn.reduce((acc, {name, phoneNumbers, emails}) => {
return [...acc, {
'name': name,
'phone': phoneNumbers[0]['number'].replace('+', ''),
'email': emails[0].email
}];
}, []);
console.log(arrayOut);