Updating array object properties within nested for loops in JavaScript can be challenging

Exploring nested loops:

for(let i = 0; i < availabilities.length; i++){
    if(availabilities[i].round === 1){
        // Identify objects with the same event_team_user_id and update status property
        let indices = helperService.findArrayIndices(availabilities, 'event_team_user_id', availabilities[i].event_team_user_id);
        for(let x = 1; x < indices.length; x++){
            availabilities[x].status = availabilities[i].status;
            console.log(availabilities[x]);
        }
    }
}
console.log(availabiities);

The code above aims to locate array objects linked to a specific round (e.g., round 1) and then synchronize the status property of other array objects that share the same event_team_user_id property.

console.log(availabilities[x]); within the loops correctly displays the array object, yet console.log(availabiities); presents an array where modifications made to the status property in the loops are not captured. Why are these changes not reflected in the saved array objects?

Answer №1

Assuming that `availabiities` is just a typo and you meant to refer to `availabilities`, your second `for` loop in the code snippet provided seems to have some issues. It appears that you're not properly utilizing the indices returned from the `helperService`. To access the correct index of `availabilities`, you should use `indices[x]`, with `x` starting at 0.

let availabilities = [
  {
    round: 1,
    event_team_user_id: 1,
    status: 'shouldmatch'
  },
  {
    round: 2,
    event_team_user_id: 2,
    status: 'shouldnotchange'
  },
  {
    round: 3,
    event_team_user_id: 1,
    status: 'shouldchange',
  },
  {
    round: 4,
    event_team_user_id: 3,
    status: 'shouldnotchange',
  },
  {
    round: 5,
    event_team_user_id: 1,
    status: 'shouldchange'
  }
];


for(var i = 0; i < availabilities.length; i++){
    if(availabilities[i].round === 1){
        // Return the indices of all objects which share the same event_team_user_id property
        var indices = [2, 4];
        for(var x = 0; x < indices.length; x++){
            const curr = indices[x];
            availabilities[curr].status = availabilities[i].status;
        }
    }
}
console.log(availabilities);

Answer №2

Seems like there was a typo mistake

before

console.log(availabiities);

after

console.log(availabilities);

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 for animating elements to move on scroll while navigating through the webpage

I came across a fascinating website that has a unique scrolling effect. As you scroll down the page, only the elements and images move while the page itself remains static, creating an interesting visual effect. I tried to replicate this on my own websit ...

Can you explain the variance between the two state updates in React?

Currently enrolled in a React course where the instructor is diving into state updates. I'm struggling to grasp the internal differences between these two code snippets, provided below for reference: Snippet that updates state directly class Counter ...

The issue of `Console.log` displaying as undefined arises after subscribing to a provider in Ionic3

In the process of implementing the Spotify api into my Ionic 3 app, I encountered an issue where the data retrieved appears as undefined when attempting to log it. Let me share some code and delve deeper into the problem. Here is the function getData() tha ...

Tips for repeatedly clicking a button over 50 times using Protractor

Is it possible to click the same button more than 50 times using a loop statement in Protractor? And will Protractor allow this action? Below is my locator : var nudge= element(by.xpath("//a[@class='isd-flat-icons fi-down']")); nudge.click(); ...

Finding the correct placement for importing 'reflect-metadata' in Next.js version 14.1.0

I am currently integrating tsyringe for dependency injection in my Next.js 14.1.0 application using the new App Router. However, I am facing an issue with its functionality when adding import 'reflect-metadata'; at the beginning of my Root Layout ...

Why do Material UI components fail to render in jsdom while using Jest?

During my UI testing using Jest/React Testing Library, I encountered a peculiar issue. In one of my components, the return statement is structured as follows: const sidebarContentUp = ( <Drawer anchor="left" onClose={onMobileC ...

I struggle to format a classic HTML form dropdown menu that is populated using JavaScript

Hey everyone, I'm having an issue with styling a drop down menu that is populated by JavaScript. I've tried different things but nothing seems to be working. Any suggestions on how I can style the elements in the drop down? <form action="" me ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in: <div id="toggle" class> ... rather than: <div id="toggle" class="on"> ... I've been trying to solve this issue for about 2 hours now ...

Image not showing up in MUI React

When trying to showcase my images using the itemDate.js file: const itemData = [ { img: "../assets/photos/photoportrait.jpeg", title: 'Breakfast', }, and calling it within my Portfolio component: import * as React f ...

Tips for designing a sophisticated "tag addition" feature

Currently, I am enhancing my website's news system and want to incorporate tags. My goal is to allow users to submit tags that will be added to an array (hidden field) within the form. I aim to add tags individually so they can all be included in the ...

Is there a way to transform a JSON object into a custom JavaScript file format that I can define myself?

I have a JSON object structured as follows: { APP_NAME: "Test App", APP_TITLE: "Hello World" } My goal is to transform this JSON object into a JavaScript file for download. The desired format of the file should resemble the follo ...

Implementing pagination with complete page information using node.js and mongodb

Hello, I am currently working on implementing pagination in NodeJS and MongoDB. Check out the code I have written below: router.get("/PO_pagination", verify, async (req, res) => { console.log("req.query", req.query) try { let ...

What is the best way to transform a string into React components that can be displayed on the screen?

Stored in my database are strings that contain partial HTML content, as shown below: “Intro<br /><br />Paragraph 1<br /><br />Paragraph 2” If I want to display this string within a new <p> element, what is a straightforwa ...

Invoke the componentDidMount() method in a React Component that is not a subclass of React.Component

I have a react component that I render later in my index.js file index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render( <React.StrictMode> <App /> ...

What is the best way to implement an onReady promise in a JavaScript application?

Exploring some Advanced topics in JS I am currently diving into and there is an interesting concept that's piqued my curiosity. I've been developing a VueJS application and now I'm looking to expose certain data and even methods from Vue ou ...

Is it possible to blur all elements of a form except for the submit button?

Can someone help me with a form issue I am facing? <form> <input type="text>' <input type="submit">' </form>'' After submitting the form, I would like to blur the entire form: $(this).closest('form') ...

Retrieve custom content from a database using Laravel and Ajax when clicking on a navigation bar

Recently, I've started working with Laravel 7 and AJAX. One of the features I want to implement is a 'product's name' navbar that displays product details in a div without refreshing the page when clicked. I came across a demo showcasin ...

The response you have received is delayed by one response

I seem to be facing an issue with my Node.js server where the response I receive is always delayed by one. The response I expect to get at the time of pressing the upload button is always received one step later. After starting the Node server, the initia ...

How can I resolve a JavaScript issue that occurs when accessing a property within the same object?

Displayed below is a snippet from a much larger JavaScript object within my project. Thousands of lines have been omitted to focus solely on the area in question... Line 6 is specifically where the issue lies. Here's a concise example involving Java ...