Having trouble changing the value of a field within an object stored in an array in JavaScript/TypeScript?

I'm wrestling with what seems to be a straightforward issue, but for some reason I can't update the pos field value in the WorkSetTemplate object within an array.

Here's the code snippet:

export class WorkSetTemplate {

  static alignPositionWithDisplay(coll: WorkSetTemplate[]): WorkSetTemplate[] {
    for (let i = 0; i < coll.length; i++) {
      coll[i].pos = i + 1;
    }
    return coll;
  }

  constructor(
    public id?: number,
    public nk?: string,
    public pos?: number,
    public name?: string,
    public maintainerId?: number,
    public airworthinessDirectiveIssueNumber?: string,
    public workItemTemplates?: WorkItemTemplate[]
  ) {}

}

Let's say we begin with these sets:

https://i.sstatic.net/R2deq.png

Then, I execute the static method like this:

Sets = WorkSetTemplate.alignPositionWithDisplay(sets);

In theory, I anticipate seeing the same set arrangement, but with the pos values sequentially assigned as 1, 2, 3 (instead of 2, 1, 3).

However, no change actually occurs - the pos values remain as 2, 1, 3. Even though, if I use console.log inside the loop, I can see that the changes are happening during each iteration. It seems like the modifications are somehow discarded once the loop is exited. There must be something fundamental that I am overlooking. Any clues on where I might have gone wrong?

Answer №1

It appears that there is a missing element in this scenario, as the items are likely to change (with or without the return value assignment).

interface WorkItemTemplate {
    name: string;
}

class WorkSetTemplate {

  static alignPositionWithDisplay(coll: WorkSetTemplate[]): WorkSetTemplate[] {
    for (let i = 0; i < coll.length; i++) {
      coll[i].pos = i + 1;
    }
    return coll;
  }

  constructor(
    public id?: number,
    public nk?: string,
    public pos?: number,
    public name?: string,
    public maintainerId?: number,
    public airworthinessDirectiveIssueNumber?: string,
    public workItemTemplates?: WorkItemTemplate[]
  ) {}

}

let items = [
    new WorkSetTemplate(5, 'ABC3', 1),
    new WorkSetTemplate(5, 'XYZ1', 1),
    new WorkSetTemplate(5, 'ABC1', 1),
];

console.log(JSON.stringify(items));

// [
//   { "id": 5, "nk": "ABC3", "pos": 1 },
//   { "id": 5, "nk": "XYZ1", "pos": 1 },
//   { "id": 5, "nk": "ABC1", "pos": 1 }
// ]

// Note - the objects are modified even without assignment
WorkSetTemplate.alignPositionWithDisplay(items);

console.log(JSON.stringify(items));

// [
//   { "id": 5, "nk": "ABC3", "pos": 1 },
//   { "id": 5, "nk": "XYZ1", "pos": 2 },
//   { "id": 5, "nk": "ABC1", "pos": 3 }
// ]

Demonstration using the transpiled code:

var WorkSetTemplate = /** @class */ (function () {
    function WorkSetTemplate(id, nk, pos, name, maintainerId, airworthinessDirectiveIssueNumber, workItemTemplates) {
        this.id = id;
        this.nk = nk;
        this.pos = pos;
        this.name = name;
        this.maintainerId = maintainerId;
        this.airworthinessDirectiveIssueNumber = airworthinessDirectiveIssueNumber;
        this.workItemTemplates = workItemTemplates;
    }
    WorkSetTemplate.alignPositionWithDisplay = function (coll) {
        for (var i = 0; i < coll.length; i++) {
            coll[i].pos = i + 1;
        }
        return coll;
    };
    return WorkSetTemplate;
}());
var items = [
    new WorkSetTemplate(5, 'ABC3', 1),
    new WorkSetTemplate(5, 'XYZ1', 1),
    new WorkSetTemplate(5, 'ABC1', 1),
];
console.log(JSON.stringify(items));
WorkSetTemplate.alignPositionWithDisplay(items);
console.log(JSON.stringify(items));

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

Uploading images simultaneously while filling out a form

Currently, I have a form that requires users to fill it out and upload an image. However, there is a delay of up to 30 seconds when the user hits "Submit" due to the image size being uploaded. I'm interested in finding a way to initiate the image upl ...

Customize time formatting in Angular to accommodate localized time formats

I am utilizing Angular's localization service version 8.3.28 to support English, Spanish (Mexico) with code es-MX, and Spanish (Spain) with code es-SP While using the date pipe: {{ foo.Date | date: 'shortDate' }} The dates are changing to ...

Refreshing a Next.js page results in a 404 error

I've set up a Next.js page called page.js that can be accessed through the URL http://localhost:3000/page. However, I have a need to access this page through a different URL, namely http://localhost:3000/my-page. To achieve this, I decided to utilize ...

Maintaining the original layout upon refreshing the page

Incorporating two forms on my website, I added a button that transitions between the login and sign-up forms smoothly. The process is as follows: Initially, the login form is displayed; clicking the button switches to the sign-up form. Proceeding to subm ...

JSON parsing encountered an unexpected token "J" at the beginning of the file, causing an error at line 4 of the mail.js API

I am struggling to identify the issue at hand and determine the root cause of the problem In my efforts to create a contact form, I have encountered an unexpected outcome. When I use console.log() on the FormData object, it shows an empty array and trigge ...

React.Children does not reveal the presence of any offspring

I am looking to implement react-native-maps-clustering in my project. However, this library only accepts markers that are direct children of the maps component. An example of how it should be structured: <MapView> <Marker/> <Marker/> ...

When attempting to render a base64 string in an <img> tag using ReactJS, an error message ERR_INVALID_URL is displayed

I am currently working on displaying server-generated images (specifically matplotlib graphs) in a ReactJS module without needing to save the files on the server. To achieve this, I decided to use base64 to create an image string. When it comes time to sh ...

What could be the reason for the input.autocomplete feature failing to erase the existing history in my form? (HTML/JS)

const form = document.querySelector("#contact-form"); const feedback = document.querySelector(".feedback"); const patternName = /^[a-z A-Z]{3,25}$/; form.addEventListener("submit", (e) => { e.preventDefault(); const firstn ...

Avoid refreshing the page and maintaining the most recent data inputted

On my HTML page, I am trying to implement a button that submits a form using a function. I have set up field validations, and when I click the submit button, it shows an error message but clears out the values I entered and refreshes the form. What I want ...

Loop through the array and print out only the last item

I am struggling to get my for loop to print out every item in the array, instead of just the last item. Can't seem to figure out where I'm going wrong: var patients = ["Julia", "Kelly", "Thomas", "Clare"]; function lineOfPatients(line) { if (! ...

After using driver.execute_script, the variable results in nil

Attempting to retrieve a lengthy string of URLs separated by commas is proving challenging. The code functions correctly in the console, but when running the script, the ruby variable urls_list remains nil. require 'rubygems' require 'selen ...

The "npx prisma db seed" command encountered an issue: Exit code 1 error occurred during the execution of the command: ts-node --compiler-options {"module":"CommonJS"} prisma/seed.ts

this is a sample package.json file when I try to execute the command "npx prisma db seed", I encounter the following error: An error occurred while running the seed command: Error: Command failed with exit code 1: ts-node --compiler-options {&qu ...

Bring in solely the static variable from an ES6 module

I have a file called common.js which holds all the necessary variables and methods used in my App, including a nav-bar module (nav-bar.js) among others. Typically, every module in my app will import the entire common.js module, except for the login module ...

The server-side API is unable to transfer cookies through the NextJS application router

I'm facing an issue in my nextjs app where I am attempting to retrieve data using the async await mechanism. My code looks like this: export const getHomeData = async (tokenCalled4PublicApis: string) => { try { // const all = getCookie( ...

Incorporating an external .htm file using javascript into a designated div element

I've been attempting to load an external .htm file into a div on my main page using the code below: <a href="#file.htm" onclick="$('#content').load('file.htm')">Link</a> While this works in Firefox, it doesn't se ...

the dropdown menu toggle is not working as expected

My dropdown icon is not appearing and the menu options are not functioning properly. Despite trying to use a script to display the text when an option is clicked, it doesn't seem to be working. It appears that the toggle functionality is not working ...

When attempting to install font-awesome with meteor npm, the module 'fontawesome'" was not found

Currently working with meteor version 1.4.1.1 which has NPM support enabled. I encountered an issue after installing the npm package "font-awesome" where the console displayed an error message stating "Uncaught Error: Cannot find module 'fontawesome&a ...

Guide to adjusting the map zoom speed on Mapbox using mouse scroll

I am a user of mapbox () and I am looking to adjust the zoom speed of the map when scrolling with the mouse. It seems like the API documentation does not have an option to control the zoom speed directly, unless it is done through something like the flyTo( ...

The saving functionality of InnerBlocks in WordPress' Gutenberg editor is not working properly

My InnerBlock seems to be functioning correctly when nesting blocks on a page, saving, and viewing the page. However, upon attempting to edit the page again, I encounter a Block validation failed error: Content generated by `save` function: <div class= ...

How to Handle Jquery POST Data in Express Servers

Update Make sure to check out the approved solution provided below. I ended up fixing the issue by removing the line contentType: 'appliction/json', from my POST request. I'm facing a problem trying to send a string to Node.js/Express becau ...