What is the best way to modify a data parameter in Angular 2?

I am facing an issue while trying to change a data parameter in my component file:

this.commandList.ListesCommandesATransmettre.forEach(data => {
    this.catalogs.forEach(catalog => {
        if (catalog.Libelle === data.Catalogue) {
            if (catalog.selected === false) {
                console.log(data.isSelected)
                data.isSelected = false;
                console.log(data.isSelected)
                console.log(data);
            }
        }
    })
});

Upon running this code, the following is displayed:

true
false

However, despite displaying false, when checking the value of isSelected using console.log(data), it still shows true. Can someone help me understand why?

Answer №1

If you're experiencing a loop issue with the callback function, give this code a try

for (let item of this.commandList.ListesCommandesATransmettre) {
  for (let catalogItem of this.catalogs) {
    if (catalogItem.Libelle === item.Catalogue) {
      if (catalogItem.selected === false) {
        console.log(item.isSelected);
        item.isSelected = false;
        console.log(item.isSelected);
        console.log(item);
      }
    }
  }
}

Answer №2

Your code logic seems a bit confusing to me. What if there are multiple catalogs in this.catalogs that meet the condition? The

isSelected</​code> property might get set to false multiple times.</p>

<p>Perhaps a clearer approach could be:</p>

<pre><code>this.commandList.ListesCommandesATransmettre = this.commandList.ListesCommandesATransmettre.map(data => {
    const updatedData = Object.assign({}, data);

    // If the condition is met, set isSelected to false. Otherwise, keep its current value
    updatedData.isSelected = 
        this.catalogs.some(catalog => catalog.Libelle === data.Catalogue && !catalog.selected) ? false : updatedData.isSelected;

    return updatedData;
})

Answer №3

Give this code a try to check for proper updates. The loop will indicate which values are true or false, allowing you to verify the updated data.

this.commandList.ListesCommandesATransmettre.forEach((data, index) => {
    this.catalogs.forEach(catalog => {
        if (catalog.Libelle === data.Catalogue) {
            if (catalog.selected === false) {
                data.isSelected = false;
            }
            console.log(index + 'is selected: ' + data.isSelected)
        }
    })
});
console.log(this.commandlist);

I've observed that web browsers tend to retain only the 'most current' reference of an object in memory. Therefore, after a loop finishes, the last one to occur becomes the 'most current' reference. You might end up viewing the last object instead of the one you intend to test. If anyone has more knowledge or insights on what is actually happening, feel free to update this post.

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

How do I properly type when extending Button and encountering an error about a missing component property?

Currently in the process of transitioning from MUI v3 to v4. My challenge lies with some Button components that are wrapped and have additional styling and properties compared to the standard Material UI Button component. Ever since upgrading to v4, I&apos ...

Using Angular: filtering data streams from a date range observable object

I have a piece of code that seems to be functioning correctly, but I can't shake the feeling that it might just be working by chance due to an undocumented feature. I'm torn between questioning its validity or accepting that it is indeed designed ...

The specified type 'x' cannot be assigned to the type 'x'. Error code: 2322

I encountered an issue with the code in @/components/ui/billboard.tsx file import { Billboard } from "@/types" interface BillboardProps { data: Billboard; }; const BillboardComponent: React.FC<BillboardProps> = ({ data }) => ...

Looping through a PHP array and converting it into an SQL string using the

Let's start fresh. We begin with three tables: Transaction Table: meter_id | bay_number | trans_date_time | amount ----------+------------+----------------------------+-------- 1078 | 5 | 2013-06-03 09:59:32+10 | 5.0 ...

Creating an array in C++ with a dynamic number of elements: a comprehensive guide

Can someone help me understand how to create an array with a specified number of elements in a dynamic way? ...

Attempting to adhere to the prescribed Cypress tutorial is resulting in various errors related to being "compiled under '--isolatedModules'"

I am new to using Cypress and I have been following the helpful tutorial on testing your first application. However, I have encountered some compiler issues in the third section. Following the instructions, I created a custom command but I am receiving th ...

Upon calling set() on Map, the object returned does not conform to a Map data structure

I've been exploring the transition to using immutable.js for managing states: class Register extends Component<{}, Map<string, string>> { state = Map<string, string>(); onInputValueChange(e) { const { name, value } ...

Exploring the power of async/await and promise in TypeScript

I'm puzzled as to why the return type string in this method is showing up as a red error: exportPageAsText(pageNumber: number): string { (async () => { const text = await this.pdfViewerService.getPageAsText(pageNumber); ...

Implementing Custom Font Awesome Icons in Your Angular Project

I recently upgraded to a fontawesome subscription with a paid plan and have successfully created some custom icons. Now, I'm looking to integrate these icons into my angular app. Here are the dependencies listed in my package.json file: "@fortawe ...

Generate a commitment from the function

I know the basics of JavaScript Promise and promise chain, but I'm looking to deepen my understanding. For example, take a look at the method provided below. It's in TypeScript, but can be adjusted for JavaScript ES6. private InsertPersonInDB(p ...

Firebase Error: Page Not Found

I recently set up an Angular2 application and added Firebase using npm. I successfully imported it into my app.component.ts without any errors showing up in my text editor. The package.json file also indicates that Firebase is installed correctly. However ...

typescript create object with immutable property already set

Can you create an object literal in JavaScript and define its interface with read-only properties simultaneously? For instance let obj = { readonly prop1: 'hello', readonly prop2: 'world' } ...

PHP's for loop may not iterate through the entire array

I am currently using PHP/7.2.0beta3 and I have a requirement to develop a custom function in PHP that can reverse an array. For example, if the array is (1,2,3), the desired outcome should be (3,2,1). My initial approach was to utilize the array_pop funct ...

What is the most efficient method of incorporating a navbar into an Angular project?

What is the most effective way to display a navbar in my Angular application? Currently, I have placed my nav-bar component at the top of my app.component.html file and am using a service to determine which items in the navbar should be visible. This is ...

Here's how you can transfer the AceEditor value to the component state in ReactJS by utilizing the onClick event of a button

I'm facing a challenge implementing a customized CodeMirror using ACE Editor. I've experimented with incorporating state alongside the 'onClick' button parameter, but I haven't been successful in making it functional. import Rea ...

The search for 'Renderer2' in '@angular/core' did not yield any results

After successfully installing Angular Material in my Angular Project by following the instructions provided in the Material documentation, I encountered some issues. Specifically, when attempting to launch the application with 'npm start', I star ...

Removing an element from an array by evaluating each item within the array

Input array: ["temp/1/Lounge/empty", "temp/1/Lounge/66,66,66,66,66,66,66,66,64,64,64,64…,64,64,64,64,64,64,64", "temp/2/Lounge/empty", "temp/3/Lounge/empty"] I have a list of elements like the above. Each element consists of four parts separated by s ...

The choices in the second dropdown menu will change based on the selection made in the first dropdown menu

Currently utilizing reactJS, I have the choices for two dropdown lists named categories and items. constructor(props) { super(props) } this.state = { categories: [ { "id": 1, "category_name": ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

Want to understand the concept of "template" within the @Component decorator in Angular 7?

I am curious about the purpose of the "template" attribute within the @Component decorator. I understand how "templateURL" functions, but I have yet to experiment with including HTML directly inside a component. https://i.stack.imgur.com/W5LiB.png What a ...