What is the best way to iterate through a contacts array to generate a new array containing different objects with their own unique properties?

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);

Answer №1

There were some syntax errors in the data provided, particularly with the use of [] and assigning key-value pairs meant for objects. I have corrected this by substituting [] with {}.

To process the data, I utilized a .reduce() method to iterate through the dataset and generate the desired array output. As per your request, only the first phone number is included.

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: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97fdf8fff9c4fafee3ffd7f0faf6fefbb9f4f8fa">[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="bdded7d2d5d3ced2d3d5fddad0dcd4d193ded2d0">[email protected]</a>'
    }],
    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);

Answer №2

Your input Array has a few syntax errors which need to be corrected. Instead of using the map function, I opted for a for loop approach, resulting in the following structure.


let arrayIn = [
    {
        phoneNumbers:[
            '+3476859087',
            '+4567893214'
        ],
        lookupKey:"12345",
        company:"PHONE",
        firstName:"John",
        contactType:"person",
        name:"John Smith",
        id:"879",
        emails:[
            '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472d282f29142a2e332f07202a262e2b6924282a">[email protected]</a>'
	],
        lastName:"Smith"
    },
    {
        phoneNumbers:[
            '+3476859087',
            '+4567773214'
        ],
        lookupKey:"890744",
        company:"PHONE",
        firstName:"Carl",
        name:"Carl Johnson",
        id:"879",
        emails:[
            '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bdded7d2d5d3ced2d3d5fddad0dcd4d193ded2d0">[email protected]</a>'
	],
        lastName:"Johnson"
    }
]

 let arrayOut = []

 for(let i = 0; i < arrayIn.length; i++){
        let contact = {
            name: arrayIn[i].name,
            phone: arrayIn[i].phoneNumbers[0],
            email: arrayIn[i].emails[0]
        }
        arrayOut.push(contact);
 }

 console.log(arrayOut);

Check out my jsfiddle implementation here: https://jsfiddle.net/1brL2cz0/

I did not separate the '+' from the phone numbers, but this is something that can easily be done as needed.

Answer №3

Is this explanation helpful?

const data = [{key: 1}, {key: 2}] 

const newData = data.map(item => { 
    return {key: item.key}; 
});

console.log(newData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a new object with the first two keys of the array of objects as keys for the new object, and the third key as an array within that

I am dealing with JSON data from a csv file and need to extract Test and Result values for each object. My goal is to create an indicator array based on the matching Test and Result in each object. [{ "Test": "GGT", "Result ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...

Experiencing issues with exporting <SVG> file due to corruption

I received some downvotes on my previous post, and I'm not sure why. My question was clear, and I provided a lot of information. Let's give it another shot. My issue is with exporting <SVG> files from an HTML document. When I try to open t ...

How to execute a function *after* another function has finished running in Javascript upon page load?

I am currently using scrollsaver.js to maintain scroll positions of elements after postback. However, I have encountered difficulties in resetting the scroll position when needed. Specifically, when paging through a list, I want the scroll position to res ...

Retrieve information from a URL using an Express API

Every 45 minutes, my API receives a request: GET http://MyHost/mediciones/sigfox_libelium/{device}/{data}/{time}/{customData#trama} I need to extract {device}, {data}, {time}, and {customData#trama} from the URL and store them in separate variables. This ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

Get Facebook to recognize and display link previews for websites using ajax technology

It is commonly known that when copying a link from an HTML website onto Facebook, the platform will attempt to fetch available images as previews for the link. But what happens when the content is dynamically generated, such as with JavaScript? In this c ...

Locate the initial ancestor element that contains a specific child element on the first level

Looking to retrieve the primary parent element of a selected item that contains a checkbox as a direct child. HTML $('input[type="checkbox"]').change(function(e) { $(this) .parent() .parents("li:has(input[type='checkbox'] ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Cannot provide explicit initialization for arrays in Windows Qt 5.7 (C++)

Building upon a helpful response, I am encountering a -seemingly common- issue **C2536 : cannot specify explicit initializer for arrays** on line in line: QLineEdit * edits[3] = {&lineEditName, &lineEditGender, &lineEditRegion}; I have reviewe ...

The challenge of customizing card styling in conditional rendering with React Native

There are two primary components in this setup: homeScreen.js (the parent component) Card.js (the child component) The card component is rendered when the search is not toggled, and all necessary data is passed down as props without any rendering is ...

Is it possible to create a channel list using the YouTube API if I am not the owner of the channel? I am not getting any errors, but nothing is showing up

I am currently working on creating a channel list and playlist of videos from a Music channel that I do not own. Here is the link to the channel: https://www.youtube.com/channel/UC-9-kyTW8ZkZNDHQJ6FgpwQ/featured. My goal is to extract data from this channe ...

nodejs downloading a plethora of images

I am currently working on a project where I am generating URLs and extracting images from those URLs. For instance, I have an array object called urls ['abc.com/01.jpg', 'abc.com/01.jpg', ....... ] and similar URLs like that. My goa ...

JavaScript code for submitting form input values

Recently, I encountered an issue on my PHP page where I handle password change requests. I am struggling to implement a Javascript function that checks if the new password contains at least one special character before proceeding to update the database fie ...

Performing a file selection in Cypress without the presence of an input element in the DOM

Upon clicking the upload button, a file browser is triggered through the method provided below. To my knowledge, an element is not automatically added to the Document Object Model (DOM) unless explicitly appended to a DOM element. const inputEl = document. ...

Material UI Snackbar background color not able to be changed

Currently, I'm working on an ErrorHandler component in React.JS that displays a Material UI Snackbar whenever it catches an error. The issue I'm facing is trying to change the background color of the Snackbar to red, which seems to be problematic ...

"Mastering the Art of Placing the VuetifyJS Popover: A Comprehensive

When using VueJS with VuetifyJS material design components, how can I adjust the positioning of the Vuetify popover component to appear below the MORE button? The current placement is in the upper left corner which I believe defaults to x=0, y=0. Button: ...

Why should I consider using anonymous functions in Javascript/JQuery even when they may not seem necessary?

Allow me to clarify this further. I am currently delving into the realm of JS and Jquery after having some experience with Java/C. In these languages, I am accustomed to using functions (methods) and I am finding it challenging to comprehend why certain fu ...

Combining Codeigniter with AJAX for an efficient system

I'm facing an issue with my like system where a user can give more than one like, but only one is being registered in the database. I suspect it's related to AJAX. Here is the button code: <a class="btn btn-xs btn-white" name="btn" onclick=" ...

NodeJS with Selenium - Attempting to Choose a Button

The HTML <button class="RCK Hsu USg adn gn8 L4E kVc iyn S9z Vxj aZc Zr3 hA- Il7 hNT BG7" tabindex="0" type="submit"> <div class="KS5 hs0 mQ8 un8 tkf TB_"> <div class="xuA"> ...