JavaScript - Assigning the same value to 2 properties but console log displays them as distinct values

While iterating through an array of documents, I am encountering a strange issue where setting two properties to the same value results in them having different values when logged using console.log.

Here is the code snippet:

this.logicItem.$promise.then(() => {
    this.logicItem.getDocuments().$promise.then((docs: any) => {
        docs.forEach(element => {
            if (element.buildProgrammeActivityStatus === BUILD_PROGRAMME_ACTIVITY_STATUS.Confirmed ||
                element.buildProgrammeActivityStatus === BUILD_PROGRAMME_ACTIVITY_STATUS.Complete) {
                element.upper = true;
                element.canUpload = true;
            } else {
                element.upper = false;
                element.canUpload = false;
            }
        });
        console.log(docs);
    });
    this.logicItem.reload(true);
});

Upon reviewing the output from the console log, it appears that even though both properties are set to true, the value of canUpload remains false. Additionally, upper reflects the expected behavior only within the true block. What could be causing this unexpected behavior? Various iterations of looping methods have been attempted, yet the outcome persists.

Answer №1

I have tested the forEach statement extensively and it seems to be functioning properly. I experimented with different data sets and consistently received the desired outcomes. Have you attempted to log each element within the forEach loop? By doing so, you may uncover any potential issues. Are the elements appearing as anticipated? Additionally, can you clarify the purpose of the reload function mentioned?

Answer №2

When it comes to JavaScript arrays, the methods Array.forEach and Array.map serve different purposes. The forEach method simply iterates through an array without changing its values. On the other hand, the map method traverses the entire array and creates a new array based on certain conditions, without altering the original array. To update the array with the changes made using map, you must manually assign or rewrite the variable.

this.logicItem.$promise.then(() => {
this.logicItem.getDocuments().$promise.then((docs: any) => {
    // Replaced forEach with map
    docs = docs.map( element => {
        if (element.buildProgrammeActivityStatus === BUILD_PROGRAMME_ACTIVITY_STATUS.Confirmed ||
            element.buildProgrammeActivityStatus === BUILD_PROGRAMME_ACTIVITY_STATUS.Complete) {
            element.upper = true;
            element.canUpload = true;
        } else {
            element.upper = false;
            element.canUpload = false;
        }
        return element; // Include a return statement for each element
    });
    console.log(docs);
});
this.logicItem.reload(true);
});

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

Typescript filtering function that results in an empty array

Struggling with filtering an array in typescript and aurelia as I keep getting empty lists. For example, when searching for the keyword ra within the firstName property, I expect to retrieve the object with the name "Raja". Not sure where I'm going w ...

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...

Filtering a deeply nested object based on an array of keys in JavaScript

I have received an object and an array. My task is to filter the object so that it only contains nodes where either the key or the value matches with the keys provided in the array. For example: Array containing keys - ['student1', 'STU&apo ...

Aligning the React Navigation header component's bottom shadow/border width with the bottom tabs border-top width

Currently, I am working on achieving a uniform width for the top border of the React Navigation bottom tabs to match that of the top header. Despite my efforts, I am unable to achieve the exact width and I am uncertain whether it is due to the width or sha ...

Add fresh material to the bottom of the page using Javascript

Hey there, I'm having a bit of trouble with my page where users can post their status. I want the new posts to appear at the bottom after the older posts when the user presses the button. Currently, Ajax is placing all new posts at the top of the old ...

Tips for transferring large data without a page redirect using jQuery's post method:

Seeking advice on how to send large data via jQuery POST without redirecting the page. I'm working on a mobile chat project where communication between user app and server is done using JSON. The issue arises when dealing with big data as the jsonGet ...

What is preventing the dependency injection of AuthHttp (angular2-jwt) into a component?

UPDATE: Success! Problem Solved After much trial and error, I finally discovered the solution to my issue. It turned out that the problem lied in a simple configuration mistake. To rectify this, I made changes to both my package.json (dependencies section ...

How to extract the chosen option from a bound list within an Angular application

Our goal is to avoid using 2-way binding in our component setup: <select type="text" formControlName="region" (change)="regionChanged($event)"> <option *ngFor="let region of regionsDDL" [ngValue]="region">{{region.name}}</option> ...

Leverage the power of the React useFetch hook with an onclick/event

My component utilizes a custom reusable hook for making HTTP calls. Here is how I am using it: const { data, error, isLoading, executeFetch } = useHttp<IArticle[]>('news', []); Additionally, within the same component, there is a toggle che ...

Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" ...

Searching with jQuery UI Autocomplete

I am interested in implementing jQuery UI autocomplete to allow users to search for items on my website. I have a list of products that I want to convert into JSON data (or just include them directly in JavaScript like the jQuery UI demo does), but I&apos ...

Regex produces odd results in string processing

This particular JavaScript regular expression: homework.description = (homework.input.match(/((\(((\S\s?)\)?)*)|(about( \w*)*))/i)); When applied to the text: potato (potato) Produces this unexpected output: (potato),(potato), ...

The TypeScript compilation is missing Carousel.d.ts file. To resolve this issue, ensure that it is included in your tsconfig either through the 'files' or 'include' property

While trying to build an Angular application for server-side execution, I encountered the following errors: ERROR in ./src/app/shared/components/carousel/interface/Carousel.d.ts Module build failed: Error: /home/training/Desktop/vishnu/TemplateAppv6/src ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

I am having issues with the Okta Angular sign-in widget as it is not redirecting

Recently, I integrated the Okta angular sign-in widget into my project, but I encountered an issue. In my application, I have multiple modules including an authentication module that manages sign-in, sign-out, and sign-up functionalities. The route I ult ...

I'm having trouble installing puppeteer

I tried running the command npm i --save-dev puppeteer to set up puppeteer for e2e testing. Unfortunately, an error occurred during installation: C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer > <a href="/cd ...

Tips for turning off hash-based redirection in AngularJS

Here is a specific URL: http://www.something.com/sometest/test/#registration Some code has been written based on #registration for Internet Explorer. However, when using AngularJS, it redirects to the following URL, which disrupts the logic: http://www ...

Is the username you want available?

I am facing a challenge in my registration form validation process where I need to verify the username input using javascript and flask in python, but the implementation is unclear to me. The requirement is to utilize $.get in the javascript segment along ...

Hidden IFrame for Jquery File Upload

I was looking for a quick guide on setting up an AJAX-style file upload using a hidden iframe. Below is the section of HTML code related to the form: <div id = "file" class = "info"> <form id="file_upload_form" method="post" enctype=" ...

Implementing dynamic ID routes in React Router using JSON data

As a beginner in React, I have been working hard to improve my skills every day. However, I am currently facing a challenge with creating dynamic routes using JSON characters (specifically from Dragon Ball Z). Although my routes are set up correctly, I wo ...