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

Configuring Firefox settings in Nightwatch

Is there a way to set Firefox preferences in nightwatch? I am trying to achieve the same thing in Java using nightwatch. To set Firefox preferences in nightwatch, you can use the following code snippet: FirefoxProfile profile = new FirefoxProfile(); prof ...

Is it possible for a kraken.js backend to manipulate the content of a webpage?

Currently using kraken.js, which is an express.js framework, to construct a localized website. Within the header section, there are 3 language options provided as links. FR | EN | DE My goal is to have the link corresponding to the currently set locale ( ...

How can you determine if a user has selected "Leave" from a JavaScript onbeforeunload dialog box?

I am currently working on an AngularJS application. Within this app, I have implemented code that prompts the user to confirm if they truly want to exit the application: window.addEventListener('beforeunload', function (e) { e.preventDefault ...

How can I establish default values for 2 to 3 options in a Dropdownlist?

Is there a way to set two values as default in a dropdown list, and when the page is refreshed, the last two selected values are retained as defaults? Thanks in advance! Visit this link for more information ...

Get a webpage that generates a POST parameter through JavaScript and save it onto your device

After extensive research, I have hit a roadblock and desperately need help. My task involves downloading an HTML page by filling out a form with various data and submitting it to save the responses. Using Firebug, I can see that my data is sent over POST, ...

Is it possible in Vuetify 2 to align the items within the expansion of a v-data-table with the headers of the main component?

I am currently working on rendering a v-data-table where the expandable section serves as a "panel" title and I want the data inside the expansion to align with the headers set at the root level. Despite my efforts, I have not been able to find a way in th ...

Generate a flexible JSON array in VB.NET

Looking to generate a flexible array that can be converted into a JSON array for visualization with Morris charts. The usual approach in VB.NET is as follows: Dim xArray(2) xArray(0) = New With {Key .TradingDay = "Day1", .Seller1 = 1500, .Seller2 = 160 ...

In Vue3, I utilize the Provide and Inject feature to handle data changes without triggering a visual update. Instead, I apply a filter() function to remove an item from an

I am currently testing the usage of the provide and inject methods. I have placed the datas and del-function in the parent component to provide, and in the child component, I am dynamically rendering using v-for='data' in datas. The objective I ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

Attempting to conceal a div element along with its contents using AngularJS

I am attempting to use AngularJS to hide a div and its contents. I have defined a scope variable initialized as false and passed it to the div in order to hide it. However, the div is still visible along with its content. <script type="text/javascr ...

React.js pagination - removing empty values from an array

I'm currently working on implementing pagination logic that automatically updates the page numbers when the last index is clicked. For example: 1 2 3 4 5 If a user clicks on the number 5, it should display: 2 3 4 5 6 and so forth... I have succe ...

Display a PHP array with my customized formatting

Hello, I'm struggling with a php code that is supposed to retrieve data from a table and display it in a structured format. My goal is to have the output look something like this: id|name|id|name|id|name. However, I've tried using the implode() m ...

Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = { "@type": "Movie", "url": "/title/tt0443272/", "name": "Lincoln", "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA ...

Explaining the process of defining `this.props` and storing data in the global Redux state

I am currently diving into the world of react and Redux and I'm using a react project on GitHub called overcode/rovercode-ui as a learning tool for understanding react and Redux. As I explore this project, I have come across some intriguing questions. ...

Angular fails to detect newly added component

Just dipping my toes into the world of angular and decided to create my first app tour of heroes. However, I encountered a problem where angular wasn't recognizing a new component. Instead of throwing an error, it simply refused to render in the brows ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

Restrict user uploads to a maximum of 5 posts per minute using Jquery

Recently, I have implemented this jQuery/AJAX code snippet: var uploaded=0; if (uploaded!=0) { setInterval(function() { uploaded--; }, 60000); alert(uploaded); } $(".UploadMSub").click(function(event){ event.preventDefault(); ...

Prisma Hack: excluding properties in type generation

EDIT hiding fields in the TypeScript definitions may pose a hidden danger: inaccessible fields during development with intellisense, but accidentally sending the full object with "hidden" fields in a response could potentially expose sensitive data. While ...

NativeScript encountered an error while trying to locate the module 'ui/sidedrawer' for the specified element 'Sidedrawer'

Currently, I am in the process of developing a simple side-drawer menu for my NativeScript application by following this helpful tutorial. I have successfully implemented it on a single page using the given code below. starting_point.xml: <Page xmlns ...

What is preventing me from assigning all padding values at once?

I attempted to modify all paddings of the html element using JavaScript, with the following code: const pd = 1 document.getElementsByClassName('board')[0].style.paddingRight = pd + 'px' document.getElementsByClassName('board') ...