Using a conditional statement to generate objects within a TypeScript loop

I'm currently working on a loop within my code that involves adding dates from an array (dates) as key/value pairs ("date":"dates[i]") to objects in another array (values).

  values.forEach((obj, i) => obj.date = dates[i]);

The issue arises when some elements in the 'values' array are null and I encounter an error message saying 'ERROR TypeError: Cannot set property 'date' of null.'

Is there a way to handle this problem using TypeScript? Can I implement a check or condition for these null values and replace them with a new object containing the missing key/value pair ("date":"dates[i]")?

For example:

values.forEach((obj, i) => 

    if (values[i] == null){
        values[i] = {}
        values[i].date = dates[i]
       }
    else {
        obj.date = dates[i]
       }
);

In case it's relevant, I am using Angular 5 components for implementing this logic, hence technically referring to them as this.values and this.dates.

I'm struggling to find a solution to this issue. Thank you for your help!

Answer №1

To achieve the desired behavior, follow these steps:

values = values.map((obj, i) => {
 if (!obj) {
   return {date: dates[i]};
 }
 obj.date = dates[i];
 return obj;
});

In this case, using Array.map is more suitable than Array.forEach because you intend to modify the objects in the array (Array.map creates a new object for each position during iteration, resulting in a new array at the end).

If you opt for Array.forEach, you can change properties of existing objects within the array, but you cannot do something like this:

values.forEach((obj, i) => {
 if (!obj) {
   obj = {date: dates[i]};
 }
 obj.date = dates[i];
});

The code inside the 'if' statement will not produce the intended result (the obj in the array will remain null), as each object is merely pointing to the corresponding element within the array.

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

Trouble arises with Webpack during the compilation of JavaScript files

I've been tackling a project in Laravel 5.3, smoothly using webpack until I decided to configure ES6 by adding babel packages to my npm module. This caused a code breakdown, prompting me to revert back to the initial setup. However, now every time I m ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

The operation to add a new user timed out after 10 seconds while buffering in the mongooseError

It appears that when I run mongoose in this code, it doesn't seem to connect to my local MongoDB database in time. The error message "mongooseError: Operation users.insertOne() buffering timed out after 10000 ms" is displayed if the insert operation i ...

Is there a way to transfer innerHTML to an onClick function in Typescript?

My goal is to pass the content of the Square element as innerHTML to the onClick function. I've attempted passing just i, but it always ends up being 100. Is there a way to only pass i when it matches the value going into the Square, or can the innerH ...

The system was unable to locate node.js with socket.io

I'm having trouble locating the file. According to the documentation I reviewed, socket.io is supposed to be automatically exposed. Encountered Error: polling-xhr.js?bd56:264 GET http://localhost:8081/socket.io/?EIO=3&transport=polling&t=LyY ...

Retrieving outcome of Solidity contract function using web3-1.0.0-beta.27

I am using web3 1.0.0-beta.27 and the pragma solidity is set to ^0.4.2. contract Charity{ function ping() public constant returns (uint) { return 200; } } Currently, I am compiling and calling it in typescript with: import * as fs ...

Determining the Width of an Image Following the Application of a CSS Class Using Javascript

I have a custom script that is able to determine whether an image is in portrait or landscape orientation. Currently, the image is identified as being in landscape mode. My goal here is to crop and center the image using absolute positioning, specifying a ...

display dynamic graphs using json data from a php backend

I'm having trouble displaying a graph using JSON data in Highcharts. Here is a sample of what I need: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-rotated-labels/ The file values ...

Display a loading indicator while rendering several Vue components

My current challenge involves loading multiple Vuetify card components based on the selected category at the top of the page. The issue arises when the array renders more than 50 cards, causing a significant delay in loading time. While I am not overly co ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

What steps should be taken to handle files in the Next JS api?

My goal is to send a docx file to the browser for client preview. I've attempted two methods: const rs = fs.createReadStream(fullPath); res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.docume ...

Automatic type inference for TypeScript getters

It appears that Typescript infers field types based solely on the private variable of a field, rather than taking into account the getter's return type union (1) or inferring from the getter itself (2): test('field type inference', () =& ...

Having trouble navigating to the link using Selenium WebDriver

I encountered an issue when trying to click on a link as it displayed an "Element Not Found" message. Below is the HTML code I used: <a id="expTo" class="formblue_link padRight10 exportLinkActive" style="display: block; margin-left: -50px; margin-b ...

Tips for accessing the individual field values of many documents within a MongoDB collection

Within my collection of documents lies a structured schema: { "_id" : ObjectId("8dcaac2eb104c2133d66f144"), "Shape" : "circle", "Color" : "blue" }, The objective is to dynamically retrieve the value of a specific field for multiple docum ...

Deciphering unconventional JSON formats

Can anyone identify the format of this JSON (if it even is JSON!) from the code snippet below? I've extracted this data from a website's HTML and now I'm struggling to parse it in C# using a JSON parser. The data requires significant preproc ...

Exploring the Functionality of the MatSlideToggleChange Event in the mat-slide-toggle Component

I want to create a form that switches between two dropdown menus using a switch. Is it possible to use the MatSlideToggleChange event from the MatSlide class to make this happen? ...

Plugin for controlling volume with a reverse slider functionality

I have been customizing the range slider plugin found at to work vertically instead of horizontally for a volume control. I have successfully arranged it to position the fill and handle in the correct reverse order. For instance, if the value is set to 7 ...

Using Aframe and JavaScript to create split id animations

I am currently working on an Aframe WebVR app and trying to develop a function that splits this.id into two parts, assigns it to a variable, and then uses setAttribute. This is the code I have: AFRAME.registerComponent('remove-yellow', { init ...

Dark Theme Issue with Angular Material's CheckBox in Mat-Menu

If you try to place a <mat-checkbox> inside a <mat-menu>, the dark themes won't apply to the text part of your <mat-checkbox>. Look at the image at the end for reference. A similar issue arises with <mat-label>s. However, the ...

How do EventEmitter<undefined> and EventEmitter<void> differ from each other?

At times, there may be a situation where we need to omit the generic variable. For example: @Component( ... ) class MyComponent { @Output() public cancel = new EventEmitter<undefined>(); private myFoo() { this.cancel.emit(); // no value ...