I am looking to map over an array to create a new array with relevant properties pulled out. I have successfully accessed my contacts on my phone and want to push the data into a more organized structure. How do I map over Array In to get to Array Out using the first values for email and phone numbers if they are present? Below is an example 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:'[email protected]'}
],
lastName:"Smith",
},
{phoneNumbers:[
{ label: 'mobile', number: '+3476859087'},
{ label: 'work', number: '+4567773214'}
],
lookupKey:"890744",
company:"PHONE",firstName:"Carl",name:"Carl Johnson",id:"879",
emails:[
{email:'[email protected]'}
],
lastName:"johnson",
}
]
I would like to end up with the following: Array out
[
{name: 'John Smith', phone: 3476859087, email: '[email protected]'},
{name: 'Carl Johnson', phone: 3476859087, email: '[email protected]'}
]
I've mapped over the array to create a contact list and as I select each one I want to push it into the state. My snack is here for reference: https://snack.expo.io/@fauslyfox110/testingreferrals
Not looking for anyone to do my snack for me, just to help me with the array portion to go from array In to array out.
Answer that worked
let arrayOut = arrayIn.reduce((acc, {name, phoneNumbers, emails}) => {
return [...acc, {
'name': name,
'phone': phoneNumbers[0]['number'].replace('+', ''),
'email': emails[0].email
}];
}, []);
console.log(arrayOut);
You had some Sytax errors in your data, mainly that you were using []
and then assigning key:value pairs, which would belong in an object - I've swapped the []
for {}
in this case
I've used a .reduce()
to iterate through your data and return the desired Array. I wasn't sure how you wanted the phone number handled, so I'm returning just the first one
const 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: '[email protected]'
}],
lastName: "Smith",
},
{
phoneNumbers: [{
label: 'mobile',
number: '+3476859087'
}, {
label: 'work',
number: '+4567773214'
}],
lookupKey: "890744",
company: "PHONE",
firstName: "Carl",
name: "Carl Johnson",
id: "879",
emails: [{
email: '[email protected]'
}],
lastName: "johnson",
}
]
let arrayOut = arrayIn.reduce((acc, {
name,
phoneNumbers,
emails
}) => {
return [...acc, {
'name': name,
'phone': phoneNumbers[0]['number'].replace('+', ''),
'email': emails[0].email
}];
}, []);
console.log(arrayOut);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加