Utilizing TypeScript and Angular2 to parse and store specific JSON data elements into an array

My current task involves retrieving JSON data from a file containing various fields. My focus is on extracting 2 specific fields and storing them in separate arrays.

SERVICE file:

getCourseType(){
    return this._http.get('url')
     .map((res:Response) => <ICourseType[]> res.json())
     .do(data =>console.log('All: ' + JSON.stringify(data)))
     .catch(this.handleError);
}

COMPONENTS.ts file:

courseType: ICourseType[];
courseName: any[] = [];
courseRoster: any[] = [];

getCourseType(){ //function called from ngOnInit()
    this.dataService.getCourseType().subscribe(
      data => this.courseType = data,
      error => this.errorMessage = <any>error);
  }

JSON file:

[
  {
    "id": 1,
    "courseTitle": "English",
    "courseNumber": 340B,
    "roster": 23,
  },
  {
    "id": 2,
    "courseTitle": "AP History",
    "courseNumber": 1420,
    "roster": 14
  },
  {
    "id": 3,
    "courseTitle": "Art",
    "courseNumber": 42A,
    "roster": 30
  }
]

Currently, I am receiving the JSON object, but if I want to gather all the courseTitle values into one array and all the roster numbers into another array for each course, should I handle that in the service or in my components?

Answer №1

Within your component's file

courseType: ICourseType[];
courseName: any[];
courseRoster: any[];

fetchCourseType(){ // This function is invoked within the ngOnInit() lifecycle hook
    this.dataService.getCourseType().subscribe(
      data => {
        this.courseType = data
        this.courseType.forEach(course=>{
             this.courseName.push(course.courseTitle);
             this.courseRoster.push(course.roster);
          })  
      },
      error => this.errorMessage = <any>error);
  }

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

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Having trouble extracting a parameter while parsing JSON in Objective-C

{"updated":1350213484,"id":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson","title":"Risultati di feed per \"Prova\"","self":[{"href":"http://www.google.com/reader/api/0/feed-finder?q\u003dPr ...

Eliminate file extensions from a URL within an IIS server

Seeking advice on how to create a consistent layout for my web pages that doesn't display the .cshtml tag in the URL. I am using JQuery, JavaScript, HTML, CSS, ASP.net (Web Pages Logic). Example URL: http:// www.site.com/page.htm New to ASP and stil ...

ngFor dynamically updates on its own

Here is a sample code snippet from the list-components: list.components.ts import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; import { EditModalComponent } from "...../edit-modal.component"; @Component({ selector: 'list& ...

Navigate a first person simulation using three.js and control your movements with the keyboard arrow

To access my reference material, please go to http://jsfiddle.net/fYtwf/ Overview I am working on a basic 3D simulation using three.js where the camera is surrounded by cubes in three dimensions. These cubes serve as a visual guide to where the camera is ...

Display JSON-like data in a neat and organized list format

I am developing an Android application that requires displaying a list of all the sensors in the device. Below is the code snippet I am using to achieve this functionality: //Read sensors and populate list sensorManager = (SensorManager) getSystemService ...

Obtain the state name after selecting it from the drop-down menu and clicking the submit button (part 3)

Read more about passing city names from PHP to JS in the second part of this discussion on Stack Overflow. This is the JSON data for states ($stateJsonObject): Array ( [0] => stdClass Object ( [stateId] => s1 [stateName] => Kuala Lumpur) ...

A comprehensive guide on enabling visibility of a variable within the confines of a function scope

In the code snippet shown below, I am facing an issue with accessing the variable AoC in the scope of the function VectorTileLayer. The variable is declared but not defined within that scope. How can I access the variable AoC within the scope of VectorTile ...

Struggling to connect jQuery Ajax with MVC 4 Controller endpoint

Currently, I am trying to implement jQuery to trigger an Ajax call upon clicking a specific button. Despite researching various examples and potential issues that may arise, I have not been able to find a solution that works for my particular scenario. Her ...

Having trouble with a file-type npm module returning null even when called with a buffer - can anyone provide insight on what mistake I

I'm currently working on a website that allows users to upload video files for storage in MongoDB. Prior to uploading and storing the files, I want to validate the file's mimetype. I attempted to use the file-type npm module, but unfortunately, i ...

Function that handles passing an Angular Dialog

I am facing a problem with my components. One of them requires an input with an array object that looks like { name: 'buttonname', click: () => {}}. I need to pass a function to the click property to open the dialog component. I am unsure of ...

Vue 3 throws an error stating: "An uncaught DOMException occurred because the string contains an invalid character."

Exploring the capabilities of vue.js on a basic website. The setup consists of a single index.html file and all JavaScript is housed in an index.js file. The website is a work in progress, but there are no blockers preventing the JavaScript functionality ...

The function of jQuery's .prop('defaultSelected') appears to be unreliable when used in Internet Explorer 9

Below is the code I am currently using: $selects = $('select'); $selects.val( $selects.prop('defaultSelected')); The purpose of this code is to reset the values of all select elements on my webpage. However, I am facing an issue in IE ...

"Unable to select all items in Mat-Selection-List with the selectAll()

I am encountering an issue while trying to incorporate selectAll() and deselectAll() functions. The error message that I am receiving can be viewed here. My implementation involves a template-driven form, and below is the snippet of my code: <mat-sele ...

What is the best way to showcase this JSON data?

Is it possible to simplify the display of data from a JSON response consisting of an array of products with attributes such as name, id, and code? I am struggling to access the products array due to my lack of proficiency in javascript/jquery. Any assista ...

Functionality is successful in one browser, yet encounters issues in another

Here is a straightforward script that allows you to choose a State which then determines the Region, and when clicked it directs you to the corresponding website. This script functions perfectly in IE. You can find the code at I've made numerous at ...

Creating a personalized tooltip in Angular for a bubble chart with ApexCharts

I'm currently working on customizing the tooltip for a bubble chart using the ApexCharts library. Here is the link to my project. ...

The ngOnInit lifecycle hook of AppComponent fails to execute upon refreshing the page

When I go to the /posts url (localhost:4200/posts), I noticed that refreshing the page doesn't trigger the ngOnInit() method of the AppComponent. ...

Transferring a JSON file between components within Angular 6 utilizing a service

I have been facing an issue in passing the response obtained from http.get() in the displayresults component to the articleinfo component. Initially, I used queryParams for this purpose but realized that I need to pass more complex data from my JSON which ...

When trying to access a URL in a next.js application using the fetch() function, the router encountered an

I recently started working on a frontend project using Next.js v13.4 app router, with an additional backend. I have organized my routes and related functionalities in the api folder within the app directory. However, when I attempt to use the fetch() funct ...