Is there a more efficient method for converting an array of objects?

Is there a more efficient way to change just one value in an array without iterating through every element?

I've included the code below where I am trying to update the contact number for each user in an array. Although my current solution works, it seems repetitive to modify only one value by looping through all elements. Is there a cleaner approach to replace just the contact number without processing other values?

const users = [
  {
    id: "1",
    name: {
      givenNames: 'SpongeBob',
      last: 'SquarePants',
    },
    contact: {
      email: '',
      phone: '+1 123-1231234'
    },
  },
  {
    id: "2",
    name: {
      givenNames: 'Patrick',
      last: 'Star',
    },
    contact: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7d3c2d4d395e7d3c2d4d389c4c8ca">[email protected]</a>',
      phone: '+1 123-123-1234',
    },
  },
  {
    id: "3",
    name: {
      givenNames: 'Eugene Harold',
      last: 'Krabs',
    },
    contact: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b2f3e282f681b2f3e282f75383436">[email protected]</a>',
      phone: '',
    },
  },
];

My implementation:

guestList() {
  const formattedArray = this.getSelectedGuests.map(user => {
     var rObj = {};
     rObj.id = user.id;
     rObj.name = user.name;
     rObj.contact = {
        email: user.contact.email,
        phone: user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''),
     };
   return rObj;
  });
  return formattedArray;
}

Updated Output:

const users = [
  {
    id: "1",
    name: {
      givenNames: 'SpongeBob',
      last: 'SquarePants',
    },
    contact: {
      email: '',
      phone: '11231231234'
    },
  },
  {
    id: "2",
    name: {
      givenNames: 'Patrick',
      last: 'Star',
    },
    contact: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63170610175123170610174d000c0c">[email protected]</a>',
      phone: '11231231234',
    },
  },
  {
    id: "3",
    name: {
      givenNames: 'Eugene Harold',
      last: 'Krabs',
    },
    contact: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="56223325226516223325227835393b">[email protected]</a>',
      phone: '',
    },
  },
];

Answer №1

If you just need to modify a property within the "contact" object, you can easily achieve this using object destructuring in JavaScript. By extracting "contact" from the rest of the object and then spreading the rest into a new object, you can create a new "contact" property with the modified content while retaining the original structure.

Here's an example snippet demonstrating this concept:

function updateContactInfo(users) {
  return users.map(({ contact, ...rest }) => ({
    ...rest,
    contacts: {
      ...contact,
      phone: contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''),
    }
  }));
}

const usersData = [{"id":"1","name":{"givenNames":"SpongeBob","last":"SquarePants"},"contact":{"email":"","phone":"+1 123-1231234"}},{"id":"2","name":{"givenNames":"Patrick","last":"Star"},"contact":{"email":"example@example.com","phone":"+1 123-123-1234"}}];

const updatedUsers = updateContactInfo(usersData);

console.log(updatedUsers);

To handle multiple immutable transformations efficiently, tools like Immer can be helpful. Immer simplifies mutating code while ensuring immutability through the use of Proxies.

Check out how Immer can be incorporated into your workflow:

const { produce } = immer;

function updateContactInfo(users) {
  return users.map(user => produce(user, draft => {
    draft.contact.phone = user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '')
  }));
}

const usersData = [{"id":"1","name":{"givenNames":"SpongeBob","last":"SquarePants"},"contact":{"email":"","phone":"+1 123-1231234"}},{"id":"2","name":{"givenNames":"Patrick","last":"Star"},"contact":{"email":"example@example.com","phone":"+1 123-123-1234"}}];

const updatedUsers = updateContactInfo(usersData);

console.log(updatedUsers);

console.log(updatedUsers[0] === usersData[0]); // Output: false (Objects are different)

Answer №2

Whenever you opt not to utilize a library that exposes Immutable objects implementation, this is the type of code you'll need to write. Depending on the JavaScript version available to you, you may be able to write slightly shorter code, but the essence remains:

guestList() {
  return this.getSelectedGuests.map(user => ({
    user.id,
    user.name,
    contact: {
        user.contact.email,
        phone: user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, ''),
    }
  }));
}

If immutability is a priority for you, I highly recommend exploring options like Immutable.js (one of the most widely used) or Seamless Immutable (not as popular, but still praised).

Answer №3

It is necessary to visit each user in order to update the contact property for every user.

I find it repetitive to iterate over every value just to change the contact object number for each user.

To avoid explicitly copying object properties, you can utilize spread syntax.

In addition, I included hyphen - and whitespace character \s in the regex pattern to achieve the desired output.

const users = [{ id: "1", name: { givenNames: 'SpongeBob', last: 'SquarePants', }, contact: { email: '', phone: '+1 123-1231234' }, }, { id: "2", name: { givenNames: 'Patrick', last: 'Star', }, contact: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa8e9f898ec8ba8e9f898ed4999597">[email protected]</a>', phone: '+1 123-123-1234', }, }, { id: "3", name: { givenNames: 'Eugene Harold', last: 'Krabs', }, contact: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f7b6a7c7b3c4f7b6a7c7b216c6062">[email protected]</a>', phone: '', }, } ];

let result = users.map(user => ({
  ...user,
  contact: {
    ...user.contact,
    "phone": user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}-\s]/g, '')
  }
}));

console.log(result);

In most scenarios, creating new arrays is not a concern as JavaScript and its platforms are optimized for such operations.

If you prefer to modify the array directly, you can use forEach() method for that purpose.

const users = [{ id: "1", name: { givenNames: 'SpongeBob', last: 'SquarePants', }, contact: { email: '', phone: '+1 123-1231234' }, }, { id: "2", name: { givenNames: 'Patrick', last: 'Star', }, contact: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86f2e3f5f2b4c6f2e3f5f2a8e5e9eb">[email protected]</a>', phone: '+1 123-123-1234', }, }, { id: "3", name: { givenNames: 'Eugene Harold', last: 'Krabs', }, contact: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01756472753241756472752f626e6c">[email protected]</a>', phone: '', }, } ];

users.forEach(user => {
  user.contact.phone = user.contact.phone.replace(/[&\/\\#,+()$~%.'":*?<>{}-\s]/g, '');
});

console.log(users);

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

Using an array to display various colors of MapKit overlays

How can I assign different colors to each bubble? These are the colors in my array: var tableColors = [UIColor(red: 220.0/255.0, green: 95.0/255.0, blue: 19.0/255.0, alpha: 0.9), UIColor(red: 255.0/255.0, green: 191.0/255.0, blue: 59.0/255.0, alpha ...

What is the best way to incorporate ng-pluralize into a loop and access the count value?

Is there a way to access the iterator in the count attribute when using ng-pluralize within a loop? <option ng-repeat="i in [1,2,3,4,5]" value="{{ i }}"> {{ i }} star<ng-pluralize count="i" when="{'1': '', 'other': ...

Decomposing LocalStorage data in React using JavaScript

How can I retrieve this element from localStorage? Although I am able to console.log(product.priceHistory), how do I access its price element? useEffect(() => { let productFromLocalStorage = localStorage.getItem(id); setProduct(JSON.parse(pro ...

analyzing properties through unit testing

Currently in the process of writing unit tests for computed properties. I have a file called fileOne.ts : export const fileOne = () => { const fx1 = computed ( () => { ... } ); const fx2 = computed ( () => { ... } ); const fx3 = comp ...

Is there a way to set a personalized callback function when closing a modal with MicroModal?

I've been utilizing MicroModal for showcasing a modal window. Everything seems to be working smoothly, except for when I try to trigger an event upon closing the modal. It's unclear to me where exactly I should implement this callback function. ...

Is it possible to access a class with protected/private fields written in TypeScript from outside the class in JavaScript?

Currently, I am delving into TypeScript classes (though my experience with OOP is limited). The following code snippet is extracted from the chapter on classes in https://www.typescriptlang.org/docs/handbook/classes.html Here's the issue at hand: I ...

What is the best way to incorporate this CodePen snippet into a Vue project?

Can anyone help me figure out how to incorporate this awesome animation from CodePen (link here: https://codepen.io/iprodev/pen/azpWBr) into a Vue project? I've tried implementing it like so: <template> <div> <canvas heigh ...

Tips for personalizing the file names generated by Vue CLI?

Struggling to locate instructions for reducing assets and generating *.min.js files with vue cli. Currently running vue cli version 4.2.3. The file extension must be *.min.js for rollbar to work properly. Any suggestions on setting up vue cli to generate ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

Swapping out the JSON data from the API with HTML content within the Vue.js application

I am currently working on a project involving Vite+Vue.js where I need to import data from a headless-cms Wordpress using REST API and JSON. The goal is to display the titles and content of the posts, including images when they appear. However, I have enco ...

What steps should I take to incorporate Google sign-in on my website and gather user information efficiently?

I am looking to add the Google sign-in button to my website. While I am knowledgeable in HTML, PHP and JavaScript are not my strong suits. My goal is to allow users to sign in with their Google account and securely store their information on my database th ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...

Using Vue and Winter CMS to enhance front end file uploading

Currently, I am facing a challenge with uploading images from a Vue frontend to WinterCMS using Illuminate/Http/Request. While Vue is able to detect the file and log the File object, I am struggling to successfully transfer it over the API. I have attempte ...

Struggling to generate a functional link with Laravel and Vue?

For the past few days, I've been facing a problem. The issue I'm encountering is this: I have created a link in my .vue page to download a simple PDF file: <a href= {{ asset('download/form.pdf') }}> Download here. </a> (Th ...

Learn how to keep sessionStorage state synchronized across ReactJS components

Within my application, there is a React component responsible for displaying a list of numbers while also keeping track of the total sum of these numbers using sessionStorage. Additionally, another component provides an <input /> element to enable u ...

The left side of the page is anchored with text content while an engaging carousel occupies the right half

Looking to create a section on the website that remains fixed while a carousel scrolls vertically. Once you reach the final slide, scrolling will continue on the page rather than changing the carousel slide. Want it to function similarly to the Creative s ...

Create an HTML and CSS code that allows you to split paragraph text into columns within a

I am seeking a way to create dynamic paragraph column text using only the Here is an example of how it could be displayed in HTML: <div> <p> Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantiu ...

Unique Text: "Personalized marker/pin for interactive map feature"

Looking to create a custom image map marker/pin with a unique bottom design resembling a union shape using CSS and Vue.js. I've attempted it myself but haven't been able to achieve the exact look as shown in the reference image. Any advice or ass ...

Angular8: Stay Updated with Real-Time Data Refreshment

I've implemented code in my app.component to retrieve all users. I'm facing an issue where if I have two windows open and perform any CRUD actions, the second window displays outdated data. To address this, I am attempting to refresh the page ev ...

Error Handling in ReactJS

Every time I try to execute my ReactJS code, an error pops up saying: Unhandled Rejection (Error): Material-UI: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e2f5f1f3e4d0a1a6bea3bea0">[email protected]</a> ve ...