I'm puzzled as to why my object remains static even after I reassign properties within a forEach loop

When retrieving an array of objects from an RX/JS call through an http backend, I encounter a peculiar issue. After making modifications to the object within a loop (attempting different methods like .forEach), the values seem to change temporarily but revert back unexpectedly.

For instance, after setting correctionQueued to true in the loop, accessing array[index] immediately afterward shows correctionQueued as false. Strangely, a new property like correctionStatus is added successfully despite not existing in the original object.

Despite attempting various looping techniques and even working on copies of the object, preexisting properties remain unchanged while new properties are added without issues.

    checklistCopy.forEach((checklistItem, index, array) => {
      if (checklistItem.crCode.isirName === correctionSetItem) {
        array[index].correctionQueued = true;
        array[index].correctionValue = mostRecentCorrection.correctionValue;
        array[index].correctionStatus = mostRecentCorrection.status;
        console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
        console.log(array[index]);
      }
    });

Although there are no errors thrown, the behavior observed is puzzling.

Initial object:

correctionQueued: false;
correctionValue: JAAMES;

--

console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
true JAMES            SENT

However, when outputting the entire object:

console.log(array[index]);

correctionQueued: false;
correctionValue: JAAMES;
correctionStatus: "SENT'; <-- This is set correctly but does not exist on original object.

Answer №1

console.log(array[index]) (specifically in Chrome) merely logs the object reference to the console. The actual values are only resolved when you expand it, meaning your console log does not capture the values at that exact moment.

To address this issue, update your console statement to:

console.log(JSON.stringify(array[index]))
. By doing so, you will notice that the values reflect accurately when the log statement is executed.

The behavior you are observing implies that there might be external factors altering the object properties back to their original value after the initial logging. Without additional context, pinpointing the cause becomes challenging. However, this should clarify why your logs display the way they do.

Answer №2

I don't quite understand your output either, but perhaps improving your code organization could offer some clarity. Consider implementing the following suggestions:

for (const item of checklistCopy) {
  item.correctionQueued = (item.crCode.isirName === correctionSetItem);
  
  if (item.correctionQueued) {
    item.correctionValue = mostRecentCorrection.correctionValue;
    item.correctionStatus = mostRecentCorrection.status;
  
    console.log('Updated checklistItem:', item);
  }
}

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

The error message "An argument was not supplied for 'e'" appeared in the header.component.tsx file at line 14, character 15

Encountering an issue in my ReactJS component: Error: header.component.tsx(14, 15): An argument for 'e' was not provided. What parameter should I be sending? Here is the component code snippet: import React, { LinkHTMLAttributes } from 'r ...

Transform two sets of string arrays into nested objects

I have a challenge where I need to take two arrays (which are arrays of integers) and create nested objects using the "Cartesian Product" in both directions. I am considering whether this is more of a permutation problem and suspect that it may involve u ...

Manipulate objects within an array by updating state with a button in React

So, I have an array of names that I want to cycle through: const data = { names: [ { name: "Jordan" // additional data }, { name: "Holly" // additional data }, { name: "Sean" // additional data ...

I can provide you with an array that includes all prime numbers found between the input numbers n1 and n2

(Please note that both n1 and n2 may be included in the array if they are prime) Additionally, the prime numbers in the array must be in ascending order. public int[] findPrimes(int start, int stop){ int flag = 0; int k = 0; int arr[] = ...

The modal popup will be triggered by various button clicks, each displaying slightly different data within the popup

As a newcomer to Angular 4, I have encountered an interesting challenge. Currently, my code consists of two separate components for two different modals triggered by two different button clicks (Add User and Edit User). However, I now face the requiremen ...

organize elements of numpy array into designated "containers"

Suppose I have an array in numpy containing integers, like this: a = numpy.array([1, 6, 6, 4, 1, 1, 4]) My goal is to organize these items into "bins" based on their values. In other words, each bin will categorize all indices of a that share the same va ...

How to leverage tsconfig paths in Angular libraries?

While developing an Angular library, I made configurations in the tsconfig.lib.json file by adding the following setup for paths: "compilerOptions": { "outDir": "../../out-tsc/lib", "target": "es2015", "declaration": true, "inlineSources ...

Implementation of Repetition Function

When working with the TypeScript example above, I encountered 2 errors. The first error was related to `i` in the second console.log due to the use of the 'let' keyword. The second error was regarding 'test' in the first line, stating i ...

Having trouble generating a mock constructor for the user model

While attempting to simulate my user model in order to test my service, the nest console is throwing a TypeError. I am unsure of how to properly 'emulate' the constructor of the user model. user.service.spec.ts import { Test, TestingModule } fro ...

Retrieve a value from a list in robot automation framework

I am trying to retrieve the values from a list that I have declared called @{EMAIL_LIST with 3 values in it) My code snippet looks like this: : FOR ${a} IN RANGE 0 3 \ Input Text id=username @{EMAIL_LIST}[a] However, I am encou ...

Guide to assigning unique identifiers to all elements within an array using JavaScript

I have an array of objects with numeric keys that correspond to specific data values. I am attempting to restructure this object in a way that includes an 'id' field for each entry. Here is the original object: [ { "1": "data1", "5": "d ...

Unable to return to the previous page after using React Router's Redirect feature

Situation: The current issue in the app is that it redirects the user from PageA to ErrorPage if certain data is not found on PageA using react-router redirect. However, when the user is on the ErrorPage and tries to navigate back using the browser back bu ...

How to utilize ngFor for multiple inputs in Angular 4

Apologies for my poor English, I'll do my best to explain my issue. Here's the problem: I'm using ngFor on an Input element, but when I enter data, it gets repeated in all the fields and I can't figure out why. <div *ngFor=" ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

Refresh the Angular component following updates to the store

Working with NGRX/Redux for the first time, I am puzzled by why my component fails to update after adding a new item to an array in the store. Within my main component, these properties are defined: productLines$: Observable<ProductionLine[]>; produ ...

Issues with Next.js and Framer Motion

My component is throwing an error related to framer-motion. What could be causing this issue? Server Error Error: (0 , react__WEBPACK_IMPORTED_MODULE_0__.createContext) is not a function This error occurred during page generation. Any console logs will be ...

Locating the maximum value in a matrix using double pointer arrays

Can you help me find the maximum element in a matrix using functions? Function details are as follows: int getMax(int **matrix, int rows, int columns) The first parameter is a pointer to the matrix. The second parameter is the number of rows. The third p ...

GitLab pipeline reveals failure in Angular testing

I'm encountering an issue with my pipeline, where a front-end unit test is failing in the pipeline but passes locally when running the 'yarn test' command. Below is my test file: import { async, ComponentFixture, TestBed } from '@angu ...

Utilizing a configuration file with Vue's `use` method

Within my index.ts file, I am setting up the configuration for the Google reCAPTCHA component using a specific sitekey: Vue.use(VueReCaptcha, { siteKey: 'my_redacted_sitekey' }); This setup occurs prior to the initialization of the new Vue({ ...

How can I hide a mat card in Angular when the array is empty?

Below is the code snippet from my Angular HTML file: <mat-card *ngFor="let getCartDetail of getCartDetails" style="margin-bottom: 1em; " > <div class="card-container"> <mat-card-ti ...