What is the best way to extract and connect data from a JSON file to a dropdown menu in Angular 2+?

Here is an example of my JSON data:

{
    "Stations": {
        "44": {
            "NAME": "Station 1",
            "BRANCH_CD": "3",
            "BRANCH": "Bay Branch"
        },
        "137": {
            "NAME": "Station 2",            
            "BRANCH_CD": "5",
            "BRANCH": "Beach Branch"        
        }
    }
}

I am looking for a way to extract the "NAME" and "BRANCH" values from each "Station" and display them in separate dropdown lists.

The framework I am using is Angular 4. Below is the code snippet that retrieves the station data:

 this.apiService.getStations().subscribe(data => {
      this.stationList = data.Stations;
     }, err => {
      this.errorFetchingStations = err;
      console.log("Error getting list of stations " + err);
    })

When I log this.stationList into the console, it appears in this format:

{44:{NAME: "Name of station", BRANCH: "Name of branch"}}
{137:{NAME: "Name of station", BRANCH: "Name of branch"}}

and so forth.

However, attempting to bind the stationList to my select element results in an error message:

ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

    <select class="form-control">
        <option *ngFor="let station of stationList" [value]="station.NAME">{{station.NAME}}</option>
      </select>

Answer №1

If you're encountering issues with key value pairs in objects when using ngFor, you can resolve this by converting it into an array with the code provided below:

this.apiService.getStations().subscribe(data => {
      this.stationList = Object.values(data.Stations); // converts object values into an array
     }, err => {
      this.errorFetchingStations = err;
      console.log("Error getting list of stations " + err);
    })

Answer №2

If you want to convert the stationList into an array, you can achieve this by utilizing Object.values(data.Stations) as shown below:

When calling this.apiService.getStations().subscribe(data => {
  var stations = data.Stations;
  this.stationList = Object.values(stations);
}, err => {
  this.errorFetchingStations = err;
  console.log("An error occurred while retrieving the list of stations: " + err);
})

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

Update the input type from string to data in MONGO DB format

Is there a way to efficiently convert the inspection_date field in my database from string to date for all objects, similar to the structure below? {"name": "$1 STORE", "address": "5573 ROSEMEAD BLVD", "city": "TEMPLE CITY", "zipcode": "91780", "state": "C ...

Exploring Typescript: A guide to iterating through a Nodelist of HTML elements and retrieving their values

I'm struggling to retrieve values from a Nodelist of input elements. Can anyone help me out? let subtitleElements = document.querySelectorAll( '.add-article__form-subtitle' ); ...

Locating the source of a JSON parsing error

Currently, I am in the process of developing a web application that enables users to upload data in JSON format. The method I am using to read local JSON files is as follows: function loadJSON(url, callback) { // set MIME type to avoid XML parsing in Fi ...

Attempting to convert numerical data into a time format extracted from a database

Struggling with formatting time formats received from a database? Looking to convert two types of data from the database into a visually appealing format on your page? For example, database value 400 should be displayed as 04:00 and 1830 as 18:30. Here&apo ...

Refreshing Components upon updates to session storage - Angular

Currently, I am in the process of developing a build-a-burger website using Angular. The ingredients and inventory need to be updated dynamically based on the selected location. Users can choose the location from a dropdown menu in the navigation bar. The ...

Can a decorator be added to a Typescript class after it has been created?

Is it possible to update a class with inversify's @injectable decorator after it has been created? My use case involves using a mocking library like ts-auto-mock to generate a mock for me, and then applying the @injectable decorator to bind the mock t ...

What causes the lack of minlength validation when the form is in its initial state?

Check out the code snippet below: <input [(ngModel)]="someProperty" minlength="5" /> I recently ran my app and used the browser debugger tool to inspect the state of this input field. Surprisingly, I noticed that it was marked as ...

The search for 'partition' in 'rxjs' did not yield any results

Recently, I attempted to incorporate ng-http-loader into my Angular project. After successfully installing the ng-http-loader package, I encountered an error during compilation. The specific error message displayed was: export 'partition' was ...

The Angular Serviceworker does not store the index.html file in its cache

When my app goes offline, it doesn't work properly due to the angular serviceworker failing to cache my index.html file (although it does cache other files like js, css, manifest, and ico). The issue only occurs when the outputPath is within my git/nx ...

Restrict the amount of XML data while converting JSON to XML with PHP

I have successfully used this code to convert JSON data into XML format. However, I am facing an issue where the XML file generated contains 200 records, but I only want to limit it to 50. My goal is to create an XML file with only the latest 50 records fr ...

The number pipe is unable to interpret the given value, either because it is outside of the allowable range or cannot be

An error occurred while processing the specified value, it seems to be either unparsable or out of the acceptable range. Whenever I apply formatting with a pipe to a number in my object, I encounter this warning and the value fails to display. However, on ...

unable to see the new component in the display

Within my app component class, I am attempting to integrate a new component. I have added the selector of this new component to the main class template. `import {CountryCapitalComponent} from "./app.country"; @Component({ selector: 'app-roo ...

Transform JSON attribute string into a JSON data structure

Here is a struct I am working with: type ResponseStatus struct { StatusCode int Message string Data string `json:"data"` } type Pets struct { Id int `json:"id"` Name string `json:"name"` Age int `json:"age"` ...

Despite using Enzyme to locate a component again, the expected prop value is still not being returned

Two components are involved here - a modal and a button that is meant to open the modal by setting its isOpen prop to true. The initial state of the modal is set to false, but when the button is clicked, it should change to true. While everything works fi ...

Having trouble utilizing a function with an async onload method within a service in Angular - why does the same function work flawlessly in a component?

I successfully created a component in Angular that can import an Excel file, convert it into an array, and display its content as a table on the page. The current implementation within the component looks like this: data-import.compoent.ts import { Compo ...

Angular Refresh Tokens

I've developed a service for calling APIs from my Angular application. Within this service, I've defined the ROOT_URL and TOKEN variables and assigned values to them. Following the declaration, there are several GET methods to access APIs using ...

Modify visibility within a subclass

Is there a way to modify property visibility in a child class from protected to public? Consider the following code snippet: class BaseFoo { protected foo; } class Foo extends BaseFoo { foo = 1; } new Foo().foo; It seems that this change is pos ...

"Manipulating values in an array with a union type: a guide to setting and

I am currently working on creating an array that can have two different value types: type Loading = { loading: true } type Loaded = { loading: false, date: string, value: number, } type Items = Loading | Loaded const items: Items[] = ...

Swiping in Angular2 gets a new twist with Swiper typings

Having trouble importing typings for Swiper into my Angular 2 project. After installing Swiper and its typings using npm, I tried including Swiper in my component like this: import { Swiper } from 'swiper'; However, Atom displays an error: ...

Enhancing CKEditor functionality with Angular 2 for improved textarea usage

Check out this Plunker example: https://plnkr.co/edit/aUBtpe?p=preview When using CKEditor, the value of the content variable does not update when changes are made to the textarea. It remains the same as the original page.content variable that was obtaine ...