Extracting a single property from an object and placing it into an array in Angular 2

Here is the object structure that I am working with:

export class HourPerMonth {
    constructor(
        public year_month: string,
        public hours: string,
        public amount: string
    ) { };
}

My goal is to extract only the hours from this object and store them in an array.

private hourPerMonth: HourPerMonth[];
private hoursArray: Array<any>;

getChartData() {
    this.chartService.getHoursPerMonth().subscribe(source => {
        this.hourPerMonth = source;
        this.hoursArray = ?
    });
}

Any suggestions on how to achieve extracting the hours from the object into the hoursArray?

Answer №1

Utilize Array.prototype.map:

this.hoursArray = source.map(object => object.hours);

It can also be done this way:

private hoursArray: Array<string>;

Or in a simpler form:

private hoursArray: string[];

Answer №2

You can try this approach to solve your issue.

declare hourPerMonth: HourPerMonth[];
declare hoursArray: Array<any> = [];

fetchChartData() {
   this.chartService.fetchHoursPerMonth().subscribe(result => {
       this.hourPerMonth = result;
       this.hourPerMonth.forEach(hourItem => {
          this.hoursArray.push(hourItem.hours);
       }
   });
}

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

Issue with Formik Material UI Keyboard Date Picker not correctly formatting the text input

I have been working on creating a custom DatePicker component specifically designed for use within Formik forms. When an initial Date value is passed to the field, I want it to remain empty until the user either types or selects a date from the Picker. I ...

Obtaining data objects with Angular 2 from JSON

Recently, I received a URL that includes data arrays in JSON format. My goal is to retrieve and utilize all elements within it: However, when attempting this, I end up with everything but nothing specific. For instance: How can I access data.name or data. ...

It is not possible to access an object's properties using bracket notation when the index is a variable

Is there a way to convert the JavaScript code below into TypeScript? function getProperties(obj) { for (let key in obj) { if (obj.hasOwnProperty(key)) { console.log(obj[key]); } } } I've been trying to find a solution but it seems t ...

Issue encountered when using await in Tensorflow.js sample code with TypeScript

After going through the official tensorflow.js documentation, I attempted to test this example using typescript with tensorflow.js While trying to execute the code snippet provided in the tensorflow.js documentation, I encountered an error related to the ...

In Angular, the dropdown in reactive forms will not populate unless there is some interaction with the form

I'm facing an issue with a form that includes 3 dropdowns getting data from an API. The problem is that the dropdowns do not bind data unless I click on them (blur on any field in the form). Here is my HTML: <form [formGroup]="dropdownsForm&q ...

How can I bypass additional ngIf checks in the Angular template if a variable is null?

I have this code snippet in my template: <div class="icon-action" *ngIf="node == null ? false : node.data && node.data.name && !node.parent.data.virtual" (click)="delete(node)"> ...

How can I gather information from members who have already signed up?

I have a form that submits data to the Angular Firebase database. Once the form is submitted, I want to display the previously submitted data in the form if the user signs in again. Below is my .ts file: import { Component, OnInit } from '@angular/c ...

Ways to boost performance in an Angular 6.0 application

https://i.stack.imgur.com/Rq9Y2.jpg We have recently developed a cutting-edge application using Angular 6, hosted on an Apache 2.4 server. To ensure our website is properly crawled by search engines, we set up a local "prerender" instance. Initially, we t ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

What is the process of transforming two forms into components and then integrating those components into a view in Angular 5?

Currently, I have two forms running smoothly on the same component as shown in InfoAndQualificationComponent.ts import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from "@angular/forms"; @Component({ selector: ...

Navigating through multiple pages in Angular2 with Rails5

Typically, in Rails development, I would use will_paginate and be done with it. However, my current project involves using Rails5 solely as an API, while the front-end is entirely Angular2. I've explored NG Bootstrap4's Pagination, but I'm ...

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

The different kinds of 'min' properties do not align. In this case, the type 'null' cannot be replaced with the type 'number' or 'undefined'

To install ngx-currency, you can run the following command: npm install ngx-currency. Next, copy and paste the code snippet below into the app.module.ts file under the section labeled set option globally... import { CurrencyMaskInputMode, NgxCurrencyMo ...

Customize column header values for Excel/CSV export with ag-grid

In my application, I am utilizing ag-grid which includes two buttons 'Download Excel' and 'Download CSV' at the top of the grid. When a user clicks on either button, the data from the grid should be downloaded in the respective file for ...

Trouble updating React Context state when attempting to utilize token from cookies

From my understanding, the typical method of maintaining context state in a React web application involves storing the user's information in a token within local storage or a cookie. Upon each page load, this token is retrieved to reset the context st ...

The TypeScript compiler remains silent when a declaration is missing

Encountered an unusual issue in my NodeJS project that I need help with. I suspect there is a simple solution hidden in tsconfig.json. Currently, I am working with TypeScript v1.7.3. The file test1.ts includes a variable declaration: // test1.ts let a = ...

Select items displayed next to each other with varying number of columns in HTML

Users can select a medicine for each day of their plan, with the option to choose up to 7 days. I want to dynamically show a corresponding number of Select dropdowns based on the user's selection. body { width: 500px; margin: 0 auto; ...

Edit the CSS styles within a webview

When loading the page in NativeScript using web viewing, I encountered a need to hide certain elements on the page. What is the best way to apply CSS styles to HTML elements in this scenario? Are there any alternatives that could be considered? I have been ...

Require assistance with transforming a JSON string into an object

I've been struggling with converting the JSON object returned from the service to the Directory class. The issue is that the Directory class has an 'expanded' property which is not present in the JSON object. I've tried various methods ...

Challenges Faced with Implementing Active Reports in Angular 9

After following all the necessary steps outlined in this website to integrate Active Reports with Angular 9 (), I encountered an error when trying to compile my app: ERROR in The target entry-point "@grapecity/activereports-angular" has missing dependen ...