Updating an object within an array of objects with a replacement

Having trouble updating an object in an array of objects. Here is the initial array:

myArray = [
  {id: 0, description: "some description", status: "initial status", function: someFunction()},
  {id: 1, description: "some description", status: "initial status", function: someFunction()},
  {id: 2, description: "some description", status: "initial status", function: someFunction()},
  {id: 3, description: "some description", status: "initial status", function: someFunction()}
]

When using .map and running the function, I get a new object like this:

{id: 2, description: "some description", status: "newStatus", function: someFunction()},

The goal is to update/replace the existing object in the array with the one that has the same id. It's worth mentioning that the id of each object corresponds to its index in the array.

UPDATE: .map function being used:

    myArray.map(item =>
      item.function(x => {
        x
          ? setStatus({ ...item, status: 'newStatus' })
          : setStatus({ ...item, status: 'newStatus2' });
      })
    );

This function includes a callback using Math.random to determine the new status - either newStatus or newStatus2. The function within each object triggers upon clicking a button in the UI.

Answer №1

The myArray is filled with objects that have a function: someFunction(). This means that the value stored will be the result of the function, not the actual function itself.

Therefore, when attempting to execute the function, you should only handle the returned value.

let myArray = [{ id: 0, description: "some description", status: "initial status", function: someFunction() }, { id: 1, description: "some description", status: "initial status", function: someFunction() }, { id: 2, description: "some description", status: "initial status", function: someFunction() }, { id: 3, description: "some description", status: "initial status", function: someFunction() } ];

myArray.map(item => {
   item.status = 'newStatus' + item.function;
});
console.log(myArray);

function someFunction() {
   return Math.floor(Math.random() * 10) + 1;
}


Alternatively, by removing the () from myArray.function, we can directly call the function inside our map():

let myArray = [{ id: 0, description: "some description", status: "initial status", function: someFunction }, { id: 1, description: "some description", status: "initial status", function: someFunction }, { id: 2, description: "some description", status: "initial status", function: someFunction }, { id: 3, description: "some description", status: "initial status", function: someFunction } ];

myArray.map(item => {
   item.status = 'newStatus' + item.function();
});
console.log(myArray);

function someFunction() {
   return Math.floor(Math.random() * 10) + 1;
}

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

Identify when two calendar dates have been modified

Creating a financial report requires the user to select two dates, search_date1 and search_date2, in order for a monthly report to be generated. Initially, I developed a daily report with only one calendar, where I successfully implemented an AJAX script ...

Strategies for managing a large volume of pending requests

I am looking to create a website that can notify users about events happening on the server. Here is my proposed plan: Send an asynchronous request to the server (ASP.NET) with a 600-second time-out If an event occurs on the server within those 600 secon ...

How can I monitor the "OnMouseNotMoving" event using jQuery?

Recently, I had an idea to add a fun feature for users on a webpage - displaying a layer at the mouse position when the user is not moving it, and then hiding it once the mouse starts moving again after a delay. I've managed to figure out the delay u ...

Encountered an error when attempting to load resource: net::ERR_CERT_AUTHORITY_INVALID following deployment on Vercel

I recently deployed a chatUI-app on Vercel that fetches chats from an API located at "http://3.111.128.67/assignment/chat?page=0" While the app worked perfectly in development, I encountered an issue after deploying it on Vercel where it ...

Ways to eliminate or conceal solely the play/pause symbol or button from the media player within the video tag

[Please see the screenshot attached, I am looking to remove the play/pause icon that is highlighted] [screenshot] How can I hide or remove only the play/pause button from the media player of a video tag? When I dynamically add the controls attribute using ...

Using ng-repeat in Angular JS to generate forms

Having just recently delved into angular JS, I began working on it a mere week ago. Utilizing the Angular-UI Bootstrap Tabs directive in my application, upon load, a grid displaying a list of records is presented within a static tab. Once a user selects a ...

Performing factorials on large numbers using arrays in the C programming language

In my ongoing quest to calculate factorials of very large numbers in C, such as 100!, I've been experimenting with dynamically allocating memory after determining the number of digits in the factorial. Check out my code below: int main() { int n, ...

Having issues with socket.io connectivity on my Node server

I am setting up my node server to update all connected clients with real-time information. However, when I run the code provided below, the io.sockets.on('connection') callback keeps firing constantly, flooding the console with the message Client ...

Move the final item in the list to the left

Can anyone suggest an efficient way to shift the last element of a Python list to its correct position within the list? For example, if we have a list = [1, 3, 4, 5, 6, 2], we want it to become [1, 2, 3, 4, 5, 6]. The method I attempted did not produce t ...

By default, the HTML table will highlight the specific column based on the current month using either AngularJS or JavaScript upon loading

I am working with a table of 10 products and their monthly sales data. Using Angular JS, I am looking to highlight the entire column based on the current month and year. Additionally, we will also be incorporating future expected sales data into the table. ...

Retrieving data from a remote PHP server using JavaScript

I am currently working on two separate websites. Site A is coded using only HTML and JavaScript, while site B utilizes PHP. I am trying to figure out a way to access variables from site B within site A. For example: The code for site A looks something li ...

A commitment was formulated within a handler but failed to be returned from it

After a user clicks on the button (#lfdsubmit), it triggers the function (LFD_SearchContainer()) which is expected to return a promise. However, errors are occurring at LFD_SearchContainer('EISU1870725') .then(container => { ST2.db2(contai ...

Creating React components through the use of the map function

Utilizing the hackernews api, I am attempting to extract the "data" property from my response object in order to display each story title individually on the browser. Initially, the data is structured as an array of id's representing individual storie ...

What could be causing the "length" property of undefined error when attempting to install React-Bootstrap with the command "npm i react-bootstrap"?

Currently, I am working my way through a comprehensive MERN full-stack tutorial. So far, things have been going smoothly - I used the "npx create-react-app" command to set up the react application and everything is compiling and running perfectly. Howeve ...

Is there a way to confirm if the target has been successfully removed from the element using jQuery?

$(".dropdown-toggle").click(function(event) { var target = $(event.target); if (target.is(this)) { $(this).find(".caret").toggleClass("customcaret"); } }); <div class="dropdown-toggle"> <div class="caret"></div> </div> ...

Unable to locate the specified script using node.js

Recently, I've started working with Javascript and Node.js. My current project is utilizing OpenMCT (https://github.com/nasa/openmct) and I'm facing an issue when trying to integrate a script as a plugin in an index.html file. Upon starting the N ...

Issue with jQuery in Internet Explorer causing difficulties loading images

I'm experiencing an issue with my website where all the images load on top of each other when the site is first loaded, creating a chaotic mess. The desired functionality is for the images to remain invisible until specific words are clicked, which is ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

Secure authentication with tokens in Node.js/Express and Angular (SPA)

When registering users in my application, I save their username, password, and JWT generated token in MONGO DB. Upon successful login with the correct credentials, I respond with the stored token. In the client-side controller, I utilize local storage to s ...

Firebase monitors the authentication status of a user

Trying to maintain a global state in my application based on whether the user is logged in or not has me puzzled. Should I only have a single onAuthStateChanged() in my JavaScript file to monitor state changes and manipulate HTML elements like account deta ...