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: '',
},
},
];