Update the value of a key in an object

I'm working with a map over an object containing an array of objects.

Object.values(props.roleRateOptions).map(el => {
  el.push(shift.roleRate);
  return el;
})

The resulting array of objects looks like this:

[ {id:1},{id:2},{label:3} ]

The issue arises when I use push(shift.roleRate), as it assigns a value of label instead of id. How can I change this to id? Is there any workaround, such as assigning a new id value if changing the existing one is not possible? Thank you in advance!

Answer №1

One way to update that particular value is by using an IIFE:

 el.push((({ label, ...rest }) => ({ id: label, ...rest }))(shift.roleRate));

Alternatively, you can duplicate the property like this:

 shift.roleRate.id = shift.roleRate.label;
 el.push(shift.roleRate);

Answer №2

If you need to change the structure of an array's objects, you can use the map method:

var items = [{name:"apple"},{name:"banana"},{category:"fruit"}];

var updatedItems = items.map(item => ({ item_name: item.name || item.category }));

console.log(updatedItems);

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

Incorporating commas as a number is typed by the user, such as 1,000, 10,000, 100,000, 1,000,000, 10,000,000,

As a beginner, I researched and managed to develop this code successfully. One issue I'm facing is that when users input numbers, there are no commas separating the thousands or millions. Does anyone have suggestions on how to automatically add commas ...

Attempting to divide a sentence based on the specified output criteria below

I am trying to split a sentence into individual words and create a new array. If the word is found in another array, I want to replace it with an empty string and add space where necessary. The desired output should look like this: Arr=["I want to ea ...

Use the Google Maps API to dynamically add a marker via AJAX once the map has been initialized

Although I have come across similar questions with related titles, none of the answers quite fit my needs. Here is the problem I am facing: I'm working on printing a map that contains multiple markers generated from a database. Below the map, there ...

Using ReactJS to dynamically append tags and content to react-dom and then refresh

As a newcomer to reactJS, I am currently working on building a react app presentation using spectacle. The unique aspect of this project is that the content and number of slides for the presentation are dynamic and fetched from a server. These slides come ...

Oops! The function exercises.slice is causing an error - it seems it's not recognized as a valid function

I am currently working on a fitness website using react js, but I'm encountering difficulties with the .slice() function. It's showing an error stating that exercises.slice is not a function coming from props. import React, { useEffect, useState ...

Is there a way to conceal a div class on the Payment page in Shopify?

I have encountered an issue with the code on the Shopify checkout (Payment) Page. Unfortunately, I am unable to directly edit this page within Shopify, but I have discovered that it is possible to add custom CSS or HTML code within the checkout settings of ...

Error in server file of NextJS due to Typescript issue

My current setup includes the following package versions: next v8.1.1-canary.42 @types/next v8.0.5 server.js import next from 'next'; const app = next({ dev: isDevelopment }); tsconfig.json { "compilerOptions": { "allowJs": true, ...

Creating Immersive Web Pages

I am currently generating a large amount of data in HTML for periodic reporting purposes. The table consists of approximately 10,000 rows, totaling around 7MB in size. As a result, when users try to open it, the browser sometimes becomes unresponsive due t ...

Tips and tricks for selecting a specific element on a webpage using jQuery

How can I modify my AJAX form submission so that only the content within a span tag with the id "message" is alerted, instead of the entire response page? $.ajax({ url: '/accounts/login/', data: $(this).serialize(), success: function(ou ...

Angular is having trouble parsing Json data which is resulting in a blank screen

I'm struggling with parsing a JSON file. In order to parse an array, I'm using the following code snippet: {"records":[{"id":"1","first_name":"John","last_name":"Doe"},{"id":"2","first_name":"Jane","last_name":"Doe"},{"id":"3","first_name":"Jo ...

In search of a TypeScript solution for type guarding

I'm encountering challenges with TypeScript type guarding. My goal is to confirm if path[aPath] is an array containing elements of type Type1, and then add to that array. However, even after using Array.isArray() to check whether the value is an array ...

Using Node.js to extract text from a local file on Azure using OCR technology

I recently started using the Azure OCR Service to extract text from images (https://learn.microsoft.com/de-de/azure/cognitive-services/Computer-vision/quickstarts/javascript#OCR). While things have been going smoothly so far with uploaded images, I am now ...

What is the best way to save the response data into an array outside of the current function in Node.js?

How can I efficiently store all the result data into an array called pImages? I am able to retrieve the results, but I believe using an async function would be more suitable. However, I am unsure of how to implement it. Any assistance would be greatly appr ...

The Node.js Express Server runs perfectly on my own machine, but encounters issues when deployed to another server

I've encountered a strange issue. My node.js server runs perfectly fine on my local machine, but when I SSH into a digital ocean server and try to run it there, I get this error. I used flightplan to transfer the files to the new machine. deploy@myse ...

The server-side PHP script may not always successfully respond to an Ajax call from the client

Whenever I try to access my index.html site, there are times when the Ajax request is made to call the PHP on the server in order to display the dynamic content. But for some reason, it only works intermittently when I manually refresh the page using the a ...

JavaScript - Fetch POST request is being terminated - Windows Error 10053

Seeking help for my JavaScript project course. The function is aborting during the fetch process. Chrome is the browser being used to test the project. It was intermittently "sending" before, but now it's not working at all. Had to run the app in Chro ...

Check to see if the specified value is present within the array of embedded documents for the user

Given the User's ID, I aim to determine if they have a groceryList item with a matching name value of "foo". Currently, my query is returning results even when the name doesn't match, likely due to the existence of other values. How can I modify ...

What is the best way to utilize props in ReactJS to establish a condition that enables me to modify the state of my application?

Within my project, I have the "App" component serving as the parent and the Hero component which features an image along with left and right arrow functionalities. In order to achieve the desired functionality, I aim to utilize the right arrow to incremen ...

Deactivating choices in Autoselect from Material UI

I am attempting to implement a feature in the autocomplete of material ui where options are disabled based on a specific condition. Each table row contains an autocomplete field, and when an option is selected in one row, it should be disabled in the next ...

Can the MUI lineplot graph be made to appear smoother?

https://i.sstatic.net/zvm4H.png I am currently exploring various techniques to enhance the smoothness of the graphs displayed in the provided Image. Despite trying multiple methods, I have yet to discover a solution that significantly improves the aesthe ...