Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase.

My goal is to consolidate all query results under a single key called this.guestPush.

Within my project, there is a multiple select element with different user levels - specifically 4, 6, and 9.

The issue arises when I select one level, as the resulting object gets saved in the guestPush array. However, upon selecting another level, an error occurs:

The error message displayed is as follows:

ERROR TypeError: this.guestPush[("filter" + i)].push is not a function

Below you can see the relevant code snippet:

  guestPush: any[] = new Array;

  level.forEach((lvl, index) => {

    this.db.object(`levelsUsers/${lvl}/users`)
      .subscribe(users => {

        if (this.guestPush['filter_' + i]) {
          this.guestPush['filter_' + i].push(users);
        } else {
          this.guestPush['filter_' + i] = users;
        }

      }, err => console.log(err));

  });

Edit:

The 'users' object comprises user entries that match the filter criteria:

Object {-KmSjAaxdCUvrPEQ8InI: Object, $key: "users", $exists: function}
  -KmSjAaxdCUvrPEQ8InI: Object
    admin:"false"
    description:"desc"
    ...
    ...
    verified:false
  __proto__:Object
  exists:function ()
  $key:"users"
  __proto__:Object

By executing this.guestPush[i] = users;, an object like the following is generated:

[Object]
 0:Object
 -KmSjAaxdCUvrPEQ8InI: Object
    admin:"false"
    description:desc"
    ...
    ...
    verified:false
    __proto__:Object
  $exists:function ()
  $key:"users"
  __proto__:Object
 length:1
 __proto__:Array(0)

Hence, moving forward, I aim to append any new user objects alongside -KmSjAaxdCUvrPEQ8InI, or any other value under the 0 key.

Answer №1

It appears that you are receiving an array response and assigning it to an object:

this.guestPush['filter_' + i] = users;

Therefore, this.guestPush['filter_'+ i] is now of type array. If you intend to add another users object to it, you would essentially be adding another array to the existing one. In such a scenario, shouldn't you be using concat?

if (this.guestPush['filter_' + i]) {
    this.guestPush['filter_' + i].concat(users);
} else {
    this.guestPush['filter_' + i] = users;
}

If users is not an array, then the code should be adjusted as follows:

if (this.guestPush['filter_' + i]) {
    this.guestPush['filter_' + i].push(users);
} else {
    this.guestPush['filter_' + i] = [users];
}

Answer №2

After much deliberation, I decided to employ

 the.guestPush.push({ [i]: { [key]: obj } });

Answer №3

@Ciprian : I have a suggestion based on your response.

A modification in your code is required to implement this. The following code snippet should be sufficient for you.

let prefix = 'filter_';
this.guestPush.push({ `${prefix}${i}` : users });

Answer №4

Here is the issue,

guestPush: any[] = new Array;
'filter_' + i // this will result in a string.
this.guestPush['filter_' + i])

An object can be defined as follows:

let name = {};
name['x'] = 'blah';
or name.x = 'blahblah'; // both methods achieve the same result

It seems like you are mistaking name['x'] = 'blah'; for an array, whereas it is actually object syntax.

Therefore, consider implementing a Dictionary.

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 issue of race condition in Node.js programming

I've been diving into the documentation, but I'm struggling to figure out what's going on here. I have two functions: one downloads a CSV file via a URL, and the next function takes that CSV file and converts it to JSON FileDownload.js co ...

Using headers in the fetch api results in a 405 Method Not Allowed error

I am facing an issue while attempting to make an ajax request using fetch. The response I receive is a 405 (Method Not Allowed) error. Here is how I am trying to execute it: fetch(url, { method: 'get', headers: { 'Game-Toke ...

Guide on validating an Australian phone number with the HTML pattern

When it comes to PHP, I have found it quite simple to validate Australian phone numbers from input using PHP Regex. Here is the regex pattern I am currently using: /^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ | ...

nsIProcess - Launch with Background Execution and Deferred Activation

Currently, my method of launching Firefox is as follows: var exe = FileUtils.getFile('XREExeF', []); //this provides the path to the executable var process = Cc['@mozilla.org/process/util;1'].createInstance(Ci.nsIProcess); process.init ...

Is it necessary to utilize process.env in node.js?

In my project, there is a .env file containing the following: ABC='abc' While in my app.js I can access the value abc using process.env.ABC, how can I require it to be used in my models' files? Attempting to use process.env.ABC in my model ...

Bespoke directive - Angular 2/4/5

Currently, I am using Angular 5 CLI but for some reason my custom directive is not working as expected. There are no errors showing up in the console either. I am trying to apply some styles to make the image fill the full width. Below are two different i ...

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

Ways to invoke a specific component within ReactDOM.render in React

Currently, I am facing an issue where 2 components need to be rendered present in a single div using myProject-init.js, but both are getting called at the same time. In myProject-init.js file: ReactDOM.render( <div> <component1>in compone ...

Tips for creating multiple functions within a single JavaScript function

Is there a way to combine these two similar functions into one in order to compress the JavaScript code? They both serve the same purpose but target different CSS classes. The goal is to highlight different images when hovering over specific list items - ...

What is the best way to limit input to only numbers and special characters?

Here is the code snippet I am working with: <input style="text-align: right;font-size: 12px;" class='input' (keyup.enter)="sumTotal($event)" type="text" [ngModel]="field.value" (focusin)="focusin()" (focusout)="format()" (keyup.ente ...

AngularJS view does not wait for the completion of $http.get request

Within my controller, the code snippet below is present... $scope.products = dataService.getJsonData(); console.log($scope.products); The corresponding code in my dataservice is as follows: .service('dataService', function ($http) { t ...

Is there a way to remove an event listener once the associated button has been clicked within the given code?

Is there a way to prevent this event from triggering once the "dispensed" button is clicked in another module? Here is the code snippet: stopDrugOrder(e: Event, drugOrder: any, drugName: string) { const confirmDialog = this.dialog.open(SharedConfirmat ...

Unlocking the Power of FusionAuth in NativeScript: A Guide

While attempting to utilize a library based on nativescript documentation, I encountered an issue where certain modules like net and tls were not being automatically discovered. After using npm install to include tls and net, the problem persisted with t ...

Guide to Sending and Scheduling Notifications through HTML 5's Notification Web APIs

Is it possible to utilize Web APIs to Schedule Notifications and send them at specific times? I am working on a CMS application that allows users to schedule and send push notifications for their mobile apps. I am interested in implementing something sim ...

What is the quickest method for retrieving li data using selenium?

Greetings! Your attention to this post is greatly appreciated. I recently set out to gather insights on a particular news article. Out of the staggering 11,000 comments attached to the news piece, I was able to acquire data from approximately 6,000 commen ...

Comparison of Static Site Generation (SSG) with Server-Side Rendering and Client-Side Rendering

The lack of concrete information surrounding the inner workings of Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static Site Generation (SSG) is truly perplexing to me. Despite numerous articles that vaguely touch on these concepts, I have ...

Building a hierarchical tree structure using arrays and objects with Lodash Js

I am attempting to create a tree-like structure using Lodash for arrays and objects. I have two arrays, one for categories and the other for products, both with a common key. The goal is to organize them into a tree structure using string indexing. let ca ...

MUI Select component not displaying top border

Can anyone help me understand why the select field is behaving this way? I'm new to the project and suspect that someone may have made changes to it. https://i.sstatic.net/pB6Sx.png <mui.FormControl style={{ width: '598px' }}> ...

Creating a custom request for the Upload component in Ant Design Vue requires a specific set of steps and

I attempted to implement the solution provided in How should customRequest be set in the Ant Design Upload component to work with an XMLHttpRequest? but it doesn't seem to be working for me in Ant Design Vue. Could someone provide an example, please? ...