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

A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario: // Library.ts // Simulating a third party library export class Library { static code ...

Verify if the currentRoute begins with a specific text pattern (such as something/something/*...) in Angular

I need to prevent a loader from appearing on certain screens, so I used ngIf on routes where the loader is not necessary. Here's the code snippet from app.component.ts : <router-outlet> <app-spinner></app-spinner> <ngx-ui-load ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

What is the function return type in a NextJS function?

In my project using NextJS 13, I've come across a layout.tsx file and found the following code snippet: export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html> <head /> <body&g ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

Unexpected behavior with HashLocationStrategy

I am currently tackling a project in Angular2 using TypeScript, and I seem to be having trouble with the HashLocationStrategy. Despite following the instructions on how to override the LocationStrategy as laid out here, I can't seem to get it to work ...

Is there a way to access a component based on its route in Angular 7?

I am currently utilizing the NavigationEnd event to identify the current route after it has been changed in the following way: this.router.events.pipe( filter(event => event instanceof NavigationEnd) ).subscribe((event) => { const na ...

What is the best way to showcase a standalone JSON object within the template?

I have a detailed component that is designed to show the 5-day forecast for a specific city. I have successfully retrieved the data using the http.get(Url) method. However, I am unsure of how to bind this JSON data to my view. I am familiar with displayi ...

What is the best way to insert information into my SQLite database?

Hey there! I'm new to programming and recently started working on an IONIC App. However, I've hit a roadblock. My goal is to create a phone book feature where users can get random JSON contacts and save them to their sqlite database. Here's ...

Merging objects with identical keys into a single object within an array using Typescript

Here is the array that I am working with: Arr = [{ code: "code1", id: "14", count: 24}, {code: "code1", id: "14", count: 37}] My objective is to consolidate this into a new array like so: Arr = [{ code: "code1& ...

If every single item in an array satisfies a specific condition

I am working with a structure that looks like this: { documentGroup: { Id: 000 Children: [ { Id: 000 Status: 1 }, { Id: 000 Status: 2 ...

Tips for circumventing debounceTime in Angular

In my current setup, I am utilizing a text input along with a debounceTime pipe to ensure that server requests are not made too frequently while the user is typing: this.keyUp$ .pipe(debounceTime(500)) .subscribe(data => this.onInputChanged.emit ...

Experiencing an issue with mui/material grid causing errors

An error occurred in the file Grid2.js within node_modules/@mui/material/Unstable_Grid2. The export 'createGrid' (imported as 'createGrid2') could not be found in '@mui/system/Unstable_Grid' as the module has no exports. Desp ...

The function 'transformArticles' is not recognized as a property of the object 'Article'

I'm encountering an issue with Typescript that I need help understanding. In my code, I have a route where I am importing a class called Article like this: import { Request, Response } from "express"; const appRoot = require("app-root-path"); import ...

Ways to obtain the file path of the compiled worker.js loaded from the worker loader, along with its hash

Currently, I am working on a TypeScript React application that utilizes Babel and Webpack for compilation. I have implemented a rule to load my worker with the following configuration: config.module.rules.unshift({ test: /gif\.worker\.js$/, ...

How to utilize the CSS hover feature within an Angular directive?

Presented here is the default directive. import { Directive, Input, Renderer2, ElementRef } from '@angular/core'; @Directive({ selector: '[newBox]' }) export class BoxDirective { @Input() backgroundColor = '#fff'; con ...

Storing the state of DevExtreme DataGrid in Angular

Currently, I have integrated the DevExtreme DataGrid widget into my Angular application. Here is a snippet of how my DataGrid is configured: <dx-data-grid id="gridContainer" [dataSource]="employees" [allowColumnReordering]="true" [allo ...

Creating a Redis client in Typescript using the `redis.createClient()` function

I'm currently trying to integrate Redis (v4.0.1) into my Express server using TypeScript, but I've encountered a small issue. As I am still in the process of learning TypeScript, I keep getting red underline errors on the host parameter within th ...

There is no overload that fits this call (regarding a basic array retrieved from an api)

While attempting to utilize a .map function on a simple array (['a','b','c']) fetched using the useEffect hook, I encountered an error in TypeScript. The array elements rendered correctly when the code was executed and no erro ...