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

Tips on utilizing the identical template in ngIf

I need to display different templates based on certain conditions. For example: <template [ngIf]="item.url.indexOf('http') == -1"> <a class="ripple-effect" [routerLink]="[item.url]" *ngIf="isUserLoggedIn == true" > ...

Tips on revealing TypeScript modules in a NodeJS environment

Currently, I am working on developing a TypeScript library. My goal is to make this library compatible with both TypeScript and JavaScript Node projects. What would be the most effective approach for achieving this? Should I create two separate versions ...

What steps can I take to resolve the "this is undefined" issue in VueJS?

Whenever I include the line this.$store.commit('disconnect');, it throws a "this is undefined" error. Any suggestions on how to resolve this issue? store/index.js : export const state = () => ({ log: false, user: {token: null, id: null, u ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

`My jquery mobile application fails to trigger the pageinit or ready events`

My website consists of 3 PHP pages: one index page and two subpages for sales and products. The index page has links to these subpages. When I click on the sales link, it is supposed to load sales data either on pageinit or document ready. However, no code ...

AngularJS attempting to conceal the popup menu upon clicking outside of the designated area

My HTML structure looks like this: <div> <a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a> <div class="options_box" ng-show="$scope.show_menu"> <button>Option1</button> ... ...

Lazy loading with Vue router seems to be having issues within the Vite environment, as an error is being thrown mentioning an unknown

I have successfully implemented the code below in Vue router and it works flawlessly in Vue-CLI. import store from "./../../store/index.js"; function getView(view) { return () => import(`@/views/settings/${vi ...

Are you experiencing difficulty loading ng-view in AngularJs?

I am new to AngularJs. I am currently using a wamp server and have successfully loaded the HTML page, but unfortunately the view is not being displayed. I have added ng-app to the body as well, but still unable to load the view. <!DOCTYPE html> ...

Proceed with another ajax request only when the previous one has been successfully completed and loaded

While scrolling down and loading content into my page, I am facing an issue. The ajax executions load too quickly, causing the subsequent calls to not receive correct information from the first ajax call that is loaded into the DOM. How can I ensure that ...

Stopping a file transfer in case of browser closure or upload cancellation

When working on uploading a file asynchronously using HTML5 in MVC3, a common issue arises when dealing with large files such as 1GB. If the upload process is cancelled or the browser is closed at 50% completion, a 500MB file still gets saved in the target ...

Are there any web browsers that automatically switch to a non-SSL connection if an attempt to connect with SSL

I regularly utilize jQuery along with jQuery.ajax to make connections between pages. I am interested in establishing a connection from a non-SSL page to an SSL page using ajax. Are there any web browsers that will attempt to connect via non-SSL if the con ...

What is causing React Js to fail loading css when switching from anchor tag to link tag?

I am learning React and experimenting with creating a basic static website using HTML templates in version ^18.2.0 of React JS. Everything seems to be functioning correctly, however, I have encountered an issue with page refresh. Specifically, when I repla ...

Viewing a document generated using the Google Drive API using the Google Drive Viewer

Using the Google Drive API, I am able to generate a document and receive some URLs: alternateLink : https://docs.google.com/document/d/xxxsome_idxxxxx/edit?usp=drivesdk embedLink https://docs.goo ...

What is the process for incorporating a custom type into Next.js's NextApiRequest object?

I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error. Below is my code snippet: import { verifyJwtToken } from "../utils/verifyJwtToken.js"; imp ...

Steps for incorporating the getElementByClassName() method

I have developed an application that features a list displayed as shown below: https://i.stack.imgur.com/BxWF2.png Upon clicking each tick mark, the corresponding Book name is added to a textbox below. I desire the tick mark to be replaced by a cross sym ...

Guide on how to showcase JSON data using vanilla JavaScript within the Laravel framework

As a beginner in Laravel, I am looking to pass JSON data from my controller using vanilla JavaScript to my view blade. However, I am unsure of the steps to accomplish this. Below is an example of my controller: public function index(Request $request) { ...

Contrast between the expressions '$(<%= DDL.ID %>) and $('<%= DDL.ID %>')

I spent hours trying to attach an event to a drop-down list with no success. I even sought help in a JavaScript chat room, but couldn't find a solution. However, by randomly attempting the following code: $('<%= ddl.ID %>').bind(&apos ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

Combining Laravel with React

Currently in the process of developing a substantial real estate listings platform with react and laravel. Can you suggest which approach would be better for this project and explain why? Option 1: Implement laravel react presets and store all react compo ...

Is it possible to generate a PNG blob using binary data stored in a typed array?

I have a piece of binary data that is formatted as a PNG image. I am looking to convert it into a blob, generate a URL for the blob, and then showcase it as an image in various places where an image URL can be used, such as CSS. My initial approach invol ...