Having difficulty accessing a list of objects nested within a parent object

There is an object called "loans" with a list of objects named "items" stored within it. While I can retrieve the attributes of "loan" using page.ts, I face difficulty in extracting the attributes of the "items" object inside the "loan" object when trying to access them through "loan.items".

Despite console.log showing that "items" and its attributes are present within the "loan" object, using "loan.items" returns an empty array. My intention is to iterate through each item in "loan.items" using a for loop.

Here is a screenshot displaying what console.log(loan) returns

Here is a screenshot illustrating what console.log(loan.items) returns

In loan.page.ts:

this.loanService.getAllCurrentOrPastLoans("username", user.email, "current")
    .subscribe(data => {
        this.currentLoans = data;

        for (let loan of this.currentLoans) {
          if (loan.status != "rejected") {
            this.currentLoansNo += 1;
            for (let item of loan.items) {
              this.currentLoansItemNo += item.quantity;
            }
        }
    }
});

In loan.service.ts:

getAllCurrentOrPastLoans(whereFilter: string, whereValue: any, currentOrPast: string): Observable<any> {
  return new Observable(observer => {
    firebase.firestore().collection('loans').where(whereFilter, '==', whereValue).orderBy('duedate').onSnapshot(collection => {
      let array = [];
      collection.forEach(doc => {
          
        if (currentOrPast == 'current') {
          if (doc.data().status != 'completed') {

            // Add loan into array if there's no error
            try {
              let loan = new Loan(doc.data().username, doc.data().status, doc.data().duedate.toDate(), doc.id);
              array.push(loan);
  
              // Read subcollection '/loans/<autoID>/items'
              let dbItems = firebase.firestore().collection('loans/' + doc.id + '/items');
              dbItems.onSnapshot(itemsCollection => {
                loan.items = []; // Empty array
                itemsCollection.forEach(itemDoc => {
                  let item = new Item(itemDoc.id, itemDoc.data().quantity);
                  loan.items.push(item);
                });
              });
            } catch (error) { }
          }

        } else if (currentOrPast == 'past') {

          if (doc.data().status == 'completed') {

            // Add loan into array if there's no error
            try {
              let loan = new Loan(doc.data().username, doc.data().status, doc.data().duedate.toDate(), doc.id, doc.data().returnstatus);
              array.push(loan);
  
              // Read subcollection '/loans/<autoID>/items'
              let dbItems = firebase.firestore().collection('loans/' + doc.id + '/items');
              dbItems.onSnapshot(itemsCollection => {
                loan.items = []; // Empty array
                itemsCollection.forEach(itemDoc => {
                  let item = new Item(itemDoc.id, itemDoc.data().quantity);
                  loan.items.push(item);
                });
              });
            } catch (error) { }
          }

        }


      });
      observer.next(array);
    });
  });
}

Answer №1

Essentially, your code seems to be returning the full response but is having trouble accessing the nested array.

Firstly, create a new variable called:

loanItems: any = [];

Then update your code like so:

this.loanService.getAllCurrentOrPastLoans("username", user.email, "current")
    .subscribe(data => {
        this.currentLoans = data;
        this.loanItems = data.items;

        for (let loan of this.currentLoans) {
          if (loan.status != "rejected") {
            this.currentLoansNo += 1;
            for (let item of this.loanItems) {
              this.currentLoansItemNo += item.quantity;
            }
        }
    }
});

Try running that and check the outcome.

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

Retain annotations for assigned types in d.ts files

When compiling declarations for the code snippet below using Typescript v5.0.4, I encounter an issue: type SomeType<T> = { field: T; }; const getInstance = <T>( value: T ): SomeType<{ [K in keyof T]: T[K]; }> => { return { ...

Harnessing the Power of Webpack, TypeScript, and Sequelize: A Comprehensive Guide

After revising my query, I'm still encountering the same issue. The technologies I am utilizing include webpack, TypeScript, and Sequelize. My aim is to integrate Sequelize into a TypeScript backend file. I have successfully installed Sequelize and ...

Issue with Ionic Framework Typescript: `this` variables cannot be accessed from callback functions

Is it possible for a callback function to access the variables within this? I am currently working with d3.request and ionic 3. I can successfully make a REST call using d3.request, but I am facing difficulty when trying to assign the response to my this. ...

Switch the order to Ascending from Alphabetical in Ionic

Currently, I am fetching JSON data from a WordPress blog using a controller. The categories are being displayed alphabetically, but I would prefer them to be displayed in ascending order. Is there an easy way to achieve this? I am still getting familiar w ...

Retrieve user information by their unique user ID from a MongoDB database using a Node, Express, and TypeScript API

Currently, I am working on a Node JS and Express with TypeScript API project. In this project, I need to retrieve data stored by a specific user from MongoDB based on their user ID. This is a snippet from my DataRouter.ts: router.get('/:userId', ...

The type 'Requireable<string>' cannot be matched with the type 'Validator<"horizontal" | "vertical" | undefined>'

code import * as React from 'react'; import * as PropTypes from 'prop-types'; interface ILayoutProps { dir?: 'horizontal' | 'vertical' }; const Layout: React.FunctionComponent<ILayoutProps> = (props) => ...

Angular8: Adjusting Activity Status After Leaving Page

When performing activities like upload, download, delete, and edit, I display statuses such as 'upload started' or 'upload completed'. This works perfectly when staying on the same page. However, there are instances where a user may nav ...

Exploring the world of HTTP PUT requests in Angular 4.0

I have encountered an issue with a function I wrote for sending an http put request to update data. The function is not receiving any data: updateHuman(human: Human) { const url = `${this.url}/${human.id}`; const data = JSON.stringify(human); ...

I prefer the value to switch to false whenever I navigate to a new route and then return to the previous route, as the sidebar remains open

click here for image details view image description here Struggling to set the value as false when revisiting this site. Need assistance! Could someone lend a hand, please? ...

The application denied the request to establish an insecure header with the label "Host", communicating using Ionic framework

Despite setting the access-control-allow-origin →* header in the response header from the server side, I am still unable to access the data from the Chrome browser. My approach in Ionic for loading data is as follows: var h = new Headers(); h.set("Host ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

Optimal method for establishing a variable when utilizing the @Input decorator in Angular

Imagine we have a Definition called User: export interface User { username: string; email: string; password: string; } Now, in a higher-level component, we aim to send an instance of User to a child component: <child-element [user]="in ...

What causes a standard React component with a default render prop to not pass PropTypes validation successfully?

I'm currently working on a React component with a render-prop that has a generic type. To improve usability, I want to set a default value for the render-prop. The code is functioning correctly, but during type-checking, I encountered a warning regard ...

The Angular service successfully provides a value, yet it fails to appear on the webpage

Currently, I am starting to dive into Angular from the ground up. One of my recent tasks involved creating a component called 'mylink' along with a corresponding service. In my attempt to retrieve a string value from the service using 'obse ...

Struggling to comprehend the intricacies of these generic declarations, particularly when it comes to Type Argument Lists

I'm currently reviewing the code snippet from the TypeScript definitions of fastify. I am struggling to understand these definitions. Although I am familiar with angle brackets used for generics, most TypeScript tutorials focus on simple types like Ar ...

What is the best way to utilize *ngSwitchWhen in a TypeScript environment?

I am currently working with Ionic2 and Angular2 and encountering an issue while trying to implement a segment using ngSwitchWhen. Unfortunately, the functionality is not working as expected and I am receiving an error message. How can I resolve this issue ...

utilize undefined files are assigned (Typescript, Express, Multer)

I am facing an issue while trying to save image uploads to a folder named "/images". The problem lies in the fact that req.files is appearing as undefined for some reason. Below is the relevant code snippet. Feel free to ask any questions, any assistance w ...

Using Angular's ElementRef to set focus on an ion-textarea: "The 'setFocus' property is not found on the 'ElementRef' type."

After developing a textarea component that automatically focuses itself when created using the ngAfterViewInit() method, everything seemed to be working perfectly as expected. ngAfterViewInit() { if(this.text.length===0){ this.theinput.setFocus(); ...

We were unable to locate the module '@reactflow/core' or its associated type declarations

After forking reactflow, I attempted to make some modifications but encountered a type error even without making any changes. https://i.sstatic.net/EyTZE.jpg My next step was to try "pnpm i @types/reactflow," but it did not resolve the issue. ...