Changing the value of an object property in JavaScript through mapping

Hey there! I've got a query. So, I have this array of objects and my goal is to convert the id of each object in the array into uppercase. Initially, I accomplished this using the following lines of code:

let x = [
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
]
x = x.map ( (a) => {return {
    id :  a.id.toUpperCase(),
    path : a.path
}})

However, I feel like this approach may not be the most efficient because if the object has additional values, they would need to be repeated in the map function. Is there a more optimal solution for achieving this task?

Appreciate any insights you can offer!

Answer №1

If you wish to make changes to the existing objects, simply update the id:

x.forEach(a => a.id = a.id.toUpperCase());

See it in action:

let x = [
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
]
x.forEach(a => a.id = a.id.toUpperCase());
console.log(x);
.as-console-wrapper {
  max-height: 100% !important;
}

If you want to create new objects in a new array (like your current code), utilize ES2018's rest property syntax:

x = x.map(a => ({...a, id: a.id.toUpperCase()}));

Example with (using y instead of x to highlight that it is a new array with new objects):

let x = [
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
]
let y = x.map(a => ({...a, id: a.id.toUpperCase()}));
console.log("x:", x);
console.log("y:", y);
.as-console-wrapper {
  max-height: 100% !important;
}

To achieve this without rest property syntax, you can use Object.assign:

let x = [
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
    { id: "anc",path: "kdsfjdklsfj"},
]
let y = x.map(a => Object.assign({}, a, {id: a.id.toUpperCase()}));
console.log("x:", x);
console.log("y:", y);
.as-console-wrapper {
  max-height: 100% !important;
}

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

Interactive website with no client-side URL management

I'm facing a challenge that I just can't seem to figure out. I've developed a website using node.js and have successfully written all the necessary code for routing, including routing for sub-domains. Some sections of the site are only acces ...

What is the best way to strip the text from a link that encompasses both text and an image using jquery?

I have a website with a list of items. Each item in the list has a link that includes both text and an image. Here is an example of the HTML structure: <li class="li-one" style=""> <a href="#" onclick="return ...

Displaying elements in a multi-dimensional array using PHP

After exploring numerous similar questions, I have yet to find a solution to my specific issue. In my database, I have a PHP nested array that needs to be printed in its entirety. The current output only displays the values of the topmost array ('name ...

Browser Integration for Real-Time Updates on GetStream io Platform

Integrating getstream.io into our framework has been a challenge. We aim to deliver activities to subscribers and provide clients with the ability to filter these activities. Unfortunately, GetStream does not support filtering on activities directly, so I ...

Is it possible to modify the express static directory path depending on the route being accessed?

I am trying to dynamically change the static path based on the route. Here is an example of what I have tried: const app = express(); const appRouter = express.Router(); const adminRouter = express.Router(); appRouter.use(express.static('/path/to/ap ...

What methods can be used to evaluate the efficiency of AngularJS in terms of DOM rendering?

Currently working on improving an AngularJS project and looking for ways to identify areas of improvement, such as memory leaks, browser performance, data rendering issues, and screen freezes. I attempted using Jmeter but it only shows page navigation spee ...

Executing a Javascript function within a PHP script

I am trying to retrieve JSON data from a JavaScript function and use it as a variable in PHP. Here is the function I have: <script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script> <script> $(fu ...

Prevent the event from bubbling up on active elements

Having trouble with stopping event propagation? Picture this situation: <table id="test"> <tbody> <tr> <td class="row"> </td> <td class="row"> </td> <td class="ro ...

Determine if a variable in a list or array is devoid of any content

I am familiar with how to determine if a list is empty (Best way to check if a list is empty) and also how to check if a numpy array is empty using this resource(How can I check whether the numpy array is empty or not?) In certain instances, I have an ele ...

What is the best way to hide a custom contextmenu in AngularJs?

I created a custom contextmenu directive using AngularJs. However, I am facing an issue where the menu is supposed to close when I click anywhere on the page except for the custom menu itself. Although I have added a click function to the document to achie ...

Comparing JSON Objects in Javascript

I'm in the process of developing a web application that retrieves data from a server and displays it to the user. The script pulls data from the server every 10 seconds, and if there's any change in the data, it alerts the user. Currently, the co ...

AngularJS - Directives cannot pass their class name into inner template

My goal is to create a directive that can apply a class name conditionally. However, I encountered an issue where the code only works if the class name is hardcoded into the class attribute. When I attempt to use it with any expression, it fails to work. ...

A dropdown menu generated from a Google Sheet script that allows for the input of custom text alongside predefined

Currently, I am working on creating a dropdown list that not only allows me to select items but also input free text. The code below enables me to choose an item from a selected range in Google Sheets. However, I am looking for a way to incorporate the f ...

Sending information from the parent component to the child Bootstrap Modal in Angular 6

As a newcomer to Angular 6, I am facing challenges with passing data between components. I am trying to launch a child component bootstrap modal from the parent modal and need to pass a string parameter to the child modal component. Additionally, I want t ...

What is the best way to add a filter to a nested array?

I am currently facing a challenge in creating a multiple filter for multiple arrays without duplicating the nested array. I am working with vuejs and some plugins that are relying on the array, so my only option is to filter it without modifying it. Using ...

JavaScript function to double the odd numbers

I'm attempting to extract the odd numbers from the given array and then double them using the reduce method, but I keep getting an undefined error. Can someone please offer some guidance? const multiplyOddByTwo = (arr) => { return arr.reduce(( ...

Searching in binary for the number closest to the target float value

Seeking assistance with a float array conundrum! I am trying to identify the closest float value to a target number within the array. My attempt involved utilizing a basic binary search algorithm in JavaScript, but I've hit a roadblock. function bina ...

We apologize for the inconvenience, but please address the upstream dependency conflict before proceeding. You may also choose to use the --force or --legacy-peer

npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="532b3e2a2c3bf48d454345584b4348454242404443472c525e7d1d010f13270">[email prote ...

I am having trouble getting the onChange handler to function properly on mobile devices

I am currently developing a React.js Progressive Web App. One of the challenges I encountered is related to an input field with an onChange event handler. <input onChange={(e) => handleInput(e)} /> Interestingly, this setup works flawlessly on ...

Validation issue with Reactive Forms not functioning as expected

My latest project involves a user signup component that I created from scratch import { Component } from '@angular/core'; import {UserManagementService} from '../user-management.service'; import {User} from "../user"; import {FormBuild ...