Unsure about Typescript object structures {} and []?

I am new to using lists and object lists in Typescript and I'm unsure of how they function. In the code snippet below, a few objects are created and some temporary values are assigned to them through a loop. However, my goal is to have the console log display the name of the second object ("image1") followed by its height (21).

There seems to be an issue with the code below as it prints out "undefined".

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  image = {};
  images = [this.image];

  constructor() {
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}

Answer №1

No issues per se, but accessing your array's objects can be simplified by using the following:

console.log(this.images[1].name)
console.log(this.images[1].height)

The names stored in the array can be utilized this way. If you're working with TypeScript and a tool that supports its language service, suggestions for available values will be provided!

Answer №2

Give this a try:

  imageList: any[] = []

  ngOnInit() {
    this.imageList = []
    for (let i = 0; i < 3; i++) {
      let img = { title: "img" + i, dimensions: 20 + i };
      this.imageList.push(img)
    }

    console.log(this.imageList);
    console.log(this.imageList[1].title);
    console.log(this.imageList[1].dimensions);
  }

Answer №3

When trying to access this.image[1] with an index [0], remember that the saved image is an object with properties like name and height.

To correctly access images, point to the index of this.images and use the property name as a key instead of a second index.

for (let i = 0; i < 3; i++) {
   const image = {name: "image"+i, height: 20+i};
   this.images[i] = image;
 }

 console.log(this.images[0].name);
 console.log(this.images[1].name);
 console.log(this.images[2].height);
...

Answer №4

Let's tackle this task using Javascript within a code snippet:

class HomeComponent {
  constructor() {
    this.image = {};
    this.images = [this.image];
    this.ngOnInit();
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(this.images[1][0]);
    console.log(this.images[1][1]);
  }

}

let x = new HomeComponent();

Now let's break it down step by step:

1 - Begin by creating an empty image object: image = {}
2 - Create an array that includes this image object: images = [{}]
3 - Set up a loop that runs three times
4 - Within the loop, modify the image object and add it to the array

As a result, you will have an array comprising of 3 elements (due to overwriting the initial value), each having distinct name and height properties.

You then attempt to access the keys "0" & "1" of the second image in the array.

However, these keys do not exist as it only consists of "name" and "height" properties!

If you wish to display the keys of the second object, you can utilize the following approach instead:

class HomeComponent {
  constructor() {
    this.image = {};
    this.images = [this.image];
    this.ngOnInit();
  }

  ngOnInit() {
    for (let i = 0; i < 3; i++) {
      this.image = {name: "image"+i, height: 20+i};
      this.images[i] = this.image;
    }

    console.log(Object.entries(this.images[1]));
  }

}

let x = new HomeComponent();

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

Development of an Angular 4 application utilizing a bespoke HTML theme

I'm in the process of creating an Angular 4 project using Angular CLI and I need to incorporate a custom HTML theme. The theme includes CSS files, JS files, and font files. Where should I place all of these files? Should they go in the asset folder? O ...

The request for XMLHttpRequest has been restricted from accessing ASP.NET CORE 2.2.0 with Angular 8 and signalr1.0.0 due to a failure in the CORS policy (Access-Control-Allow-Origin)

nugetPackage on .net core2.2.0: signalr 1.0.0 + ASP.Core2.2.0 I am utilizing angular to utilize signalr: package.json: "@aspnet/signalr": "1.1.0", my front-end Angular code: import { Component } from '@angular/core'; import * as signalR fro ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

What could be causing my Angular2 component to not properly use my template?

I have two components that I am working with. The first component is: import {Component} from 'angular2/angular2'; import {Navbar} from './navbar'; @Component({ selector: 'app' template: `<div class="col-md-12"> ...

Retrieve specific files from a Firestore collection based on a particular field

I am currently working on a web application using Angular 6 and angularfire2. I have successfully retrieved all documents in a collection, but now I need to filter those documents to only get the ones with the field role.moderator == true. private users ...

Can you explain the significance of the 'project' within the parserOptions in the .eslintrc.js file?

Initially, I struggle with speaking English. Apologies for the inconvenience :( Currently, I am using ESLint in Visual Studio Code and delving into studying Nest.js. I find it difficult to grasp the 'project' setting within the parserOptions sec ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

Struggling with module dependencies in Nest.js

I have been diving into the documentation provided on the NestJs website, but I've noticed that it can be a bit scattered. My goal is to retrieve an RPG Character from a Mongo database using TypeORM. Unfortunately, I seem to be running into dependency ...

Issue with calling a function to change the CSS color class of a button in Angular

Within my Angular code, I am attempting to set a CSS color for my button by calling a TypeScript function that will return the appropriate CSS class name. This is the code I have tried: <button style="height: 10%" class="getColor(days.date)">{{days ...

Issue: Kindly update your dependencies to the latest version of core-js@3

When trying to execute npm start, I encountered an error stating "An unhandled exception occurred: Could not find module "@angular-devkit/build-angular". I attempted to resolve this by installing it using npm install @angular-devkit/build-angular, but the ...

Mastering the Art of Mocking ControlContainer in Angular Unit Testing

Is there a way to simulate a ControlContainer instance in order to effectively test my component? One of my child components incorporates a ControlContainer within the constructor, leading to usage like this: <acr-score-card formGroupName="score">& ...

Getting Started with Icons in NativeScript and Angular: A Step-by-Step Guide

I'm having trouble incorporating icons into my nativescript + angular app for both iOS and Android. I've experimented with various methods of setting up icons, including following this tutorial, using this solution, as well as attempting to utili ...

As a quirk of TypeScript, it does not allow for returning a Tuple directly and instead interprets it as an Array

I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax: export function to(promise:Promise<any>) { return promise .then(data => [null, data]) .catch(err => [ ...

Do not send the Angular 2 HTTP request with headers

As someone new to Angular2, I am working on building a data service and trying to include headers in each request. Here is my attempt at adding headers, but for some reason they are not being sent: import { Injectable } from '@angular/core'; im ...

Is it feasible to programmatically define the onClick action for an element within a ReactNode?

Let's discuss a function called addAlert that adds messages to an array for display as React Bootstrap alerts. While most alerts are simple text, there's one that comes with an "undo the last action" link. The challenge is that when this "undo" l ...

Sorting character values in TypeScript using ascending and descending order in a JSON array

In my dataset of homes, I have the following information: var homes = [ { "h_id": "3","city": "Dallas","state": "YYYY","zip": "75201","price": "162500" }, { "h_id": "4","city": "CA","state": "ZZZZ","zip": "90210","price": "319250" }, { "h ...

Displaying the component that was provided as a parameter

I am looking to develop a custom component that can take another component as a parameter and then embed it within an NgBootstrap modal while also incorporating additional HTML elements. I am unsure if this is achievable, but my goal is to enhance modals ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

The 'Element[]' type is lacking certain properties when dealing with react children

In my code, there is a parent component passing down its children to a child component. These children can be either single nodes or arrays of nodes, and the ChildComponent renders them differently based on their type. However, when I try to render the Chi ...

Is there a way in Angular2 to append a class name from a variable to the host element without removing the current classes?

I am facing a challenge where I have a class name stored in a variable and I need to apply it to the host element of my Angular2 component. However, I am struggling to find a solution for this. While I can easily add a constant string as a class using Hos ...