Adding the `push()` method to an object at runtime in Typescript/Javascript

I'm encountering an issue when attempting to utilize the push() method to add a property to an object named counterType. The error message I receive is as follows:

Uncaught TypeError: Cannot read property 'push' of undefined

The goal is to extract specific data from a JSON file and incorporate it into the counterType object. Here is the code snippet in question:

    let ret = JSON.parse(this.responseText);
    let counterType: any = {};

    for (let i = 0; i < ret.topdownGranularities.TOPDOWN_SYSTEM_DATA.rows.length; i++) {
        let row = ret.topdownGranularities.TOPDOWN_SYSTEM_DATA.rows[i];
        let row_system = row.SYSTEM;
        if (row.hasOwnProperty("SYSTEM")) {
            counterType[row_system].push({ name: row_system, checked: true });
            // counterType[row_system] = "name: " + row_system + ", checked: " + true;
        }
    }

Although the following line successfully executes, it only appends one property during each iteration, as it simply redefines the value of counterType[row_system] repeatedly:

// counterType[row_system] = "name: " + row_system + ", checked: " + true;

The objective is to continually add

{ name: row_system, checked: true }
to the object with every iteration.

Answer №1

Substitute

let basketType: any = {};

With :

let basketType: any = [];

Because the usage calls for an array to be used and items pushed into it.

Furthermore, there is no need to specify an index when pushing:

basketType[row_system].push({ name: row_system, checked: true });

can be updated to

basketType.push({ name: row_system, checked: true });

Answer №2

Here is an example of how you can achieve this:

Define a public interface called counterTypesModel with properties name (any) and checked (boolean).
Create an empty array named counterTypesArray of type counterTypesModel.
Push an object with 'name' as row_system and 'checked' set to true into the counterTypesArray.

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

Is there a way to dynamically create a Vue component for every tier of a nested JSON object without prior knowledge of the total number of tiers available?

I am working with JSON data that includes a list of retailers, some of which have subretailers that go multiple levels deep. My goal is to use Vue to generate markup that will show the parent retailer along with any nested subretailers underneath it, simi ...

Struggling to modify a JSON value within a loop

I am currently developing a JavaScript code that involves updating one JSON based on conditions from another JSON. Below is the code I have written. const a = [{ "a": "Not Started" }, { "b": "Not Started" }, { "c": "Not Started" }, { "d": "Not S ...

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

Transmit intricate data structure to a web API endpoint using AJAX requests

When attempting to send a complex object named vm containing an object 'Budget' and an array 'BudgetDetails' populated with rows from an HTML table to my API controller using AJAX, I encounter the error message "Uncaught RangeError: Max ...

Using JavaScript to find the weekday of the same date next year

Struggling to determine the weekday of a particular date next year? Take for example Tuesday, April 19, 2016 as the given date. What we need to calculate is: TUESDAY, April 18, 2017. Consistency with weekdays is crucial in this scenario. The challenge lie ...

Ways to extract innerHTML content from a loaded element generated by using the .load() method

Check out the code snippet below: template.html : <div id="nav"> Welcome to Space </div> layout.html : <div id="content"> </div> $('#content').load("template.html #nav"); ale ...

Shuffled JSONObject for Android is an innovative feature that

The code snippet below converts a string to JSON format: json = new JSONObject( "{\"Questions\":{" + "\"1\":[\"ELSYS\",\"ELSYS2\",\"ELSYS3\",\"ELSYS4&bs ...

Navigating conflicts between packages that utilize TypeScript can be tricky. Here are some strategies for handling these situations

I recently encountered an issue while following a tutorial to create a WhatsApp clone using Meteor. The tutorial link is here The problem arose at the end of section 8 when I executed the $meteor reset command as directed. However, upon running the $ n ...

Obtaining information from AngularJS callback function in loopback: A comprehensive guide

I am trying to figure out how to retrieve the "good" array from an angular function. Here is the function I have in my Angular code: app.run(function($rootScope,Communications,$http,$filter) { $rootScope.getCommunication = function(object_type ...

display a dialogue box when clicked, containing radio buttons

I am currently developing a practice exam for students at my school. The exam consists of multiple choice questions, and I have hit a roadblock in the coding process. Being new to javascript, I am struggling to figure out how to make it function properly. ...

I simply aim to remove a single piece of news at a time, yet somehow I manage to delete more than intended

Do you have a PHP file containing a list of news items fetched from the database? Each news item has a delete link, which looks like this: echo '<a id="'.$result_news['id_news'].'" class="j_newsdelete" href="#">Delete</a ...

How can I dynamically pass a background:url using JavaScript to CSS?

I have a CSS code snippet below that I would like to dynamically change the "background:url" part using Javascript. div{ background: url('pinkFlower.jpg') no-repeat fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

What is the most effective method for leveraging Django's ORM and Django Rest Framework to serialize a queryset with nested relationships?

How can I properly construct a queryset that can be passed into a Django Rest Framework Serializer in order to receive a data/json output of related nested objects? For instance, consider the following models: class Topping(models.Model): name = model ...

Struggling to organize and paginate numbers in angularjs and facing filtering and sorting issues

I'm running into some issues with getting the paging feature to work properly while applying filters. Currently, when the filters are active, the paging numbers do not display correctly and only filter the first page of results. What I'm aiming ...

Tips to avoid the page from scrolling to the top when the menu is opened

Whenever a user taps the menu button on the page, a full-page menu opens. However, there is an issue - the main content page automatically scrolls to the top. Can you provide suggestions on how to prevent this from happening? I have already looked into a s ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

Powershell in Action with Bitbucket

It seems like there might be something simple that I'm overlooking here. The PowerShell script below contains nested JSONs in the body: Invoke-RestMethod "https://api.bitbucket.org/2.0/repositories/myworkspace/$slug" -Body @{ "scm&quo ...

It appears that the data in nodejs is not being displayed correctly by res.json

I am currently developing APIs using a local file named ads.js. The main API /api/ads that displays all the ads in JSON format is functioning correctly. However, the secondary API /api/ads/:id does not seem to be returning any data. The server is being r ...

Using ASP.NET MVC to map FormData with an array to a model class

I am currently facing an issue with mapping a list of objects in a FormData to my ASP.NET MVC Model class at the controller. I have successfully sent the FormData over to the server-side, but I am unable to bind any value. Can someone provide guidance on h ...

Passing a variable from a service to a controller in AngularJS

I recently developed a basic app that includes user authentication based on the guidelines found in this useful resource. The core components of my app are a userAccountService, which manages communication with the server, and a login controller that over ...