Create an array of arrays within a loop using TypeScript

My application contains an object with dates and corresponding time arrays. The console log output is displayed below:


32: {
1514160000: Array [ 1200, 1500 ],
1514764800: Array [ 1200, 1500 ],
1515369600: Array [ 1200, 1500 ],
1515974400: Array [ 700, 1200, 1500 ],
1516579200: Array [ 700, 1200, 1500 ],
}

Using this data, I have created a loop to generate a new array of dates with times and worker IDs as shown below (similar structure):


1514160000 :[
1200 : [32,40,56],
1500 : [32,40],
],
1514764800: [
1200 : [32,40,56],
1500 : [32,40],
]

The code snippet I wrote for this purpose creates an array of dates by dynamically assigning date values and then converting it into another array.


let allDates :any = [];
for(let pid in this.allAvailableProviders)
{
console.log(pid);
for(let slotDate in this.allAvailableProviders[pid]){
if(!Array.isArray(allDates[slotDate])){
let allDates[slotDate] :any = [];
}
}
}

The variable allAvailableProviders is an object in this context.

When running the command ng serve, I encounter the following error:

'=' expected

How can I resolve this issue?

Answer №1

Simply initializing the array without any assignment:

    for(let slotDate in this.allAvailableProviders[pid]){
      if(!Array.isArray(allDates[slotDate])){
        allDates[slotDate] = [];
      }
    }

Answer №2

The let statement is used to declare a variable, not an expression.

Instead of using any, aim to define your outer array with the correct data type, as you are aware that it will be an array of arrays.

  let allDates: any[][] = [];
  for(let pid in this.allAvailableProviders)
  {
    console.log(pid);
    for(let slotDate in this.allAvailableProviders[pid]){
      if(!Array.isArray(allDates[slotDate])){
        // Make sure to assign only arrays to avoid errors.
        // This ensures proper typing and prevents unexpected issues.
        allDates[slotDate] = [];
      }
    }
  }

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

What is the best way to customize multiselection in jqgrid?

jQuery("#grid").jqGrid({ datatype: "local", width:'auto', height: 'auto', multiselect:true, colNames:[ 'no' ], colModel:[ {name:'no', align:'r ...

How can I target and focus on a dynamically generated form in Angular 4/Ionic3?

One of the challenges I'm facing is dealing with dynamically created forms on a page. Each row consists of inputs and a button. Is there a way to select/focus on the input by clicking on the entire row (button)? It should be noted that the number of r ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

Guide on how to submit an image along with text using AJAX, PHP, and HTML

Hey there! I'm currently working on a project where I need to upload an image with comments added into a database using a combination of PHP, AJAX, and HTML. Let me show you the HTML part first: <form name="form1" enctype="multipart/form-data" ac ...

hashSync function needs both data and salt to generate the hash

I can't figure out why I am encountering this issue, I have checked the documentation and couldn't find my mistake. Any suggestions? Error: data and salt arguments required const {create} = require('./user.service'); const {genSaltS ...

A white background emerges when I select md-dropdown

Lately, I've been experiencing an issue on my website where a white background pops up whenever I click on a dropdown (md-select) in my form. Initially, it only happened with forms inside a modal, but now it's affecting dropdowns across the entir ...

When decoding a JWT, it may return the value of "[object Object]"

Having some trouble decoding a JSON web token that's being sent to my REST API server. I can't seem to access the _id property within the web token. Below is the code I'm currently using: jwt.verify(token, process.env.TOKEN_SECRET, { comp ...

What steps do I need to take to successfully integrate Firebase authentication with Angular2 FINAL?

After upgrading to Angular2 Final, I completed the migration project steps to transition everything over. Surprisingly, there were no errors during authentication; however, the issue arises post-authentication. Upon redirection back to the page, the authen ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

Building a bespoke search input for the DataTables JQuery extension

As the title indicates, I am in the process of developing a custom search box for the DataTables JQuery plugin. The default options do not suit my needs, and configuring the DOM is also not ideal as I aim to integrate it within a table row for display purp ...

Mastering the Art of jQuery Post with Iteration and Result Utilization

I am facing an issue with my code function fetchInfoFromDB() { let body = ""; let text = ""; $("tr").each(function (index) { let code = $(this).children("td:nth-child(2)"); $.post("http://urltogetdatafromdatabase.com/getinfo.ph ...

The BubbleUp technique used in a Heap implementation in the C programming language

I previously shared my heap implementation here and received valuable assistance with the add() function. I am grateful for the help, but I am still encountering issues with invalid reads and memory leaks. Any further guidance would be greatly appreciated. ...

Using createStyles in TypeScript to align content with justifyContent

Within my toolbar, I have two icons positioned on the left end. At the moment, I am applying this specific styling approach: const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', }, appBar: ...

converting code from JavaScript to Flask and then back to JavaScript, all within a single-page application

In order to make my single-page web app fully functional, I have completed the following tasks: Sent a json from .js to Flask (COMPLETED) Ran the input through a Python function called getString() and obtained a string output (COMPLET ...

Exploring the Power of TypeScript with NPM Packages: A Comprehensive Guide

I am working with a "compiler" package that generates typescript classes. However, when I attempted to run it using npm, an unexpected error occurred: SyntaxError: Unexpected token export To avoid the need for compiling local files, I do not want to con ...

Encountering a node module issue when implementing graphql in a TypeScript project

I encountered issues when attempting to utilize the @types/graphql package alongside TypeScript Node Starter node_modules//subscription/subscribe.d.ts(17,4): error TS2314: Generic type AsyncIterator<T, E>' requires 2 type argument(s). node_modu ...

Breaking apart web addresses and their attached parameters

I am attempting to extract the part of a URL that comes after the last forward slash (/) and before the querystring. While I have been successful in obtaining the last segment of the URL, I have encountered difficulty in removing the querystring from it. ...

Scanning for devices on Ionic 2/3 made simple: How to easily exclude unwanted application and Android directories

I'm currently working on a gallery application that enables users to choose images from their phone and transfer them to a kiosk. Upon loading the application, it searches the entire device for folders containing images and organizes them into an albu ...

Utilize Jquery to dynamically update form input in real time based on checkbox selections

I am working on a form that requires real-time calculation of GST (Goods and Services Tax) directly within the form (GST = Price/11) This functionality has been implemented with the following script. Additionally, the calculation needs to be adjust ...