What is the best way to retrieve a specific property from an array of objects in Angular 6 using typescript?

I am currently working on a budgeting application that incorporates an array of expenses with a price property. Each expense is defined within an Expense model in Typescript. While I can easily access the price property using ngFor loop in HTML, I'm curious if it's possible to achieve the same using a for loop directly in Typescript.

expenses.service.ts

import { Injectable } from '@angular/core';
import { Expense } from '../expenses-list/expense/expense.model';
@Injectable({
  providedIn: 'root'
})
export class ExpensesService {
  expenses: Expense [] = [
    new Expense('car payment', 350) // price
];
constructor() { }
onAddExpenseToExpenses(expense: Expense) {
  this.expenses.push(expense);
}

// EXAMPLE //
onCalculate() {
  // get prices from listed items
  // add all the prices
  // subtract income from sum of prices
}

Apologies if my explanation is not very clear, as I am relatively new to Angular 6.

Thank you for your assistance! =)

Below is the structure for my expense model:

export class Expense {
  private item: string;
  private price: number;

constructor(item: string, price: number) {
    this.item = item;
    this.price = price;
  }
}

Answer №1

If you want to loop through expenses in TypeScript, you can simply use a for loop.

First, define the expenses like this:

expenses: Array<Expense>

Then, in the constructor, add the following code:

this.expenses = new Array<Expense>()
let x = new Expense('car payment', 350);
this.expenses.add(x);
//or
this.expenses.push(x);

After setting up the expenses array, you can calculate the sum of prices in the onCalculate method using this code:

let sum = 0
for (let item of expenses) {
   sum += item.Price;
}

For more information on looping in TypeScript, you can refer to the Iterators and Generators section on the typescriptlang website.

Answer №2

JavaScript and TypeScript are very similar, except for Type and Interface features. It is beneficial to explore and refer to JavaScript documentation.

There are various methods to iterate through a loop:

Using For Loop:

let sumPrices = 0;
for (let i = 0; i < this.expenses; i++) {
  sumPrices += this.expenses[i].price;
}

Using For ... of:

let sumPrices = 0;
for (const o of this.expenses) {
  sumPrices += o.price;
}

Utilizing Array map method:

// Retrieve prices from the listed items
// Sum up all the prices
const sumPrices = this.expenses.reduce((acc, o) => acc + o.price, 0);

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

How come the inference mechanism selects the type from the last function in the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown What is the reason that T is not never (1 & 2)? Does the type always come from the last function, or can it come from one of them? ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

An issue has been encountered at the header component of an Angular web application, identified as error code

I recently created a small Angular web application and decided to create a Header component using the command line ng g c Header. https://i.sstatic.net/ZgCi0.pngI then proceeded to write a brief paragraph in the header.component.html file. <p>header ...

Error encountered within eot file using file-loader and webpack

I am facing an issue while trying to integrate React Rainbow Components with Next.js (TypeScript). I encountered a problem with importing fonts, which led me to use webpack along with the url-loader. However, despite my efforts, I keep encountering the er ...

Validating Angular input for decimal values based on specific criteria

Is there a way to limit user input to numbers with only 2 decimal places if both itemNew.UL_DATA and itemNew.LL_DATA are equal to 0 or blank? <ion-col col-2> <input (keypress)="ShowKey();" [style.display]="itemNew.UL_DATA== ...

How to Properly Initialize a Variable for Future Use in a Component?

After initializing my component, certain variables remain unassigned until a later point. I am seeking a way to utilize these variables beyond the initialization process, but I am unsure of how to do so. Below is my attempted code snippet, which throws a ...

Issues with property binding in Angular are causing problems

Suppose the app component has a variable defined for the value in the input field. However, every time the button event is triggered, the string is printed as empty and the binding does not seem to work at all. export class AppComponent { numVal =1235; ...

What is the best way to send an email with a time-sensitive code (token) using Firebase?

Currently, I am developing an application that requires sending a verification code to users before they can proceed with certain actions. For instance, when users log in to the app, they need to enter their email, password (authenticated using Firebase au ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

What role does the empty object type {} play in typescript?

In the @types/React package of the DefinitelyTyped library, I came across this definition: interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement | null; propTypes?: WeakValidationMap&l ...

"Encountered a problem while trying to follow the AngularJS2 Quickstart Guide - received error 404 stating that 'angular' is not found in

After cloning the official AngularJS Quickstart code and running npm install, I encountered a 404 error stating that 'angular' is not in the npm registry. Below is an excerpt from my npm debug log: 17 silly registry.get 'content-len ...

What is the proper way to utilize the router next function for optimal performance

I want to keep it on the same line, but it keeps giving me errors. Is there a way to prevent it from breaking onto a new line? const router = useRouter(); const { replace } = useRouter(); view image here ...

Utilize an API call to fetch data and seamlessly showcase it on the webpage using Vue.js

I have created an API and defined it in my TypeScript file const Book = { async getBookType(intID: string): Promise<Book[]> { // const intId = API.Product.getCurrentId(); const intId = ''; const response = await h ...

What is the rationale behind ngOnInit not being a private method in Angular?

After extensively checking both code samples and even the official documentation, I am still unable to find the information I need. Turning to Google has also yielded no results. The question that baffles me is: ngOnInit() { ... } Why do we use this syn ...

Looking to individually check each query parameter in Angular 6?

I'm currently struggling with managing query parameters in my Angular application. There are multiple query parameters on my search page with the following URL: /search?q=hyderbard&view=map&type=bat&brand=sg const urlParams = Observab ...

Stop unauthorized access to specific pages on ionic platform unless the user is logged in

I have a scenario where I want to redirect users from the welcome page (welcome.page.ts) when they click on the login button. If they are already logged in, they should be redirected to the home page (home.page.html). Below is the code snippet from my welc ...

Encountering an issue while running the ng build --prod command in Angular

I ran into an issue while trying to execute the command ng build --prod in Angular. I've completed my small project and now need to generate the necessary files for uploading to my hosting provider. ERROR - ANGULAR CLI C:\Users\Johan Cor ...

Combining declarations with a personalized interface using TypeScript

My goal is to enhance the express.Request type by adding a user property so that req.user will be of my custom IUser type. After learning about declaration merging, I decided to create a custom.d.ts file. declare namespace Express { export interface ...

Tips for implementing lazy loading of modals in Angular 7's module structure

In a previous project, our team utilized a single "app module" that imported all necessary components, pipes, directives, and pages at the beginning of the application. However, this structure was not ideal as the app became slower with its growth. Upon t ...

encountering issues with resolving dependency tree while attempting to create an Ionic app

Hey, I've been trying to build an ionic app but keep encountering this error that I'm unable to resolve: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! Found: <a href="/cdn-cgi/l/email-protection" ...