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

Enhance the data structure by including extra fields post JSON de-serialization using play-json-extensions

I have a scenario where my case class consists of more than 22 parameters. case class Model(a1: Int, a2: Int, a3: Int, a4: Int, a5: Int, a6: Int, ...

Transform Jupiter Tessellation (JT) documents into JSON format for display in THREE.js

Looking for guidance on rendering .JT files in THREE.js. Explored different options but haven't found a solution yet: Checked various loaders in Three.js but couldn't find one for JT files. Please advise if there's something I've ov ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

How do I identify whether a link from the API is a Nuxt link with :to or :href?

Currently, I am constructing my main menu using data from an API: <b-navbar-nav> <div v-for="result in resultsmenu" :key="result.id"> <span class="hoverlink"> <nuxt-link :to="result. ...

Setting up Datatable in Angular 2+ without relying on jQuery

I need assistance with initializing a datatable for a table that has a unique id. Can you provide guidance on the syntax to achieve this? Here is an example of my table structure: <table id="myDataTable"> <thead> <tr> ...

Which offers a more efficient approach: implementing functionalities within subscribe or in a custom operator with RxJS?

Within my angular application, I frequently utilize a pattern like this: this._store .root .pipe( ..., mergeMap(() => this._httpClient.get<IEvent[]>(`${this.ROUTE}/user/${id}`)) ) .subscribe((events: IEvent[]) => ...

Switch on ngbAccordion via TypeScript File

I need to implement a function in my component.ts file that will toggle the accordion using a button. Can you help me with the script for this? This is my HTML code: <button (click)="toggleAcc()" type="button" class="btn btn-pr ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Cross-origin resource sharing policy is rejecting the specified white-listed address in the CORS policy with the .WithOrigins

Despite having white-listed the origin http://localhost:4200/ in Startup.cs, Cors is still rejecting the request. This issue persists when making a GET request to my API and attempting to establish a connection through SignalR. Although I can bypass Cors ...

The guard check may not be enough to prevent the object from being null

Hello, I am facing an issue with the Object is possibly "null" error message in my Node.js + Express application. How can I resolve this problem? REST API export const getOrderReport = async ( req: Request<{}, {}, IAuthUser>, res: Resp ...

TypeScript Error 2304: Element 'div' is nowhere to be found - CRA TypeScript Template

I'm experiencing a problem in VSCode while working on the default create-react-app my-app --template typescript project. It seems to not recognize any HTML elements, as I keep getting the error cannot find name xxx, where 'xxx' represents th ...

Adding the expiry date/time to the verification email sent by AWS Cognito

After some investigation, I discovered that when a user creates an account on my website using AWS Cognito, the verification code remains valid for 24 hours. Utilizing the AWS CDK to deploy my stacks in the AWS environment, I encountered a challenge within ...

What is the proper way to create an array of dynamically nested objects in TypeScript?

Consider the structure of an array : [ branch_a: { holidays: [] }, branch_b: { holidays: [] }, ] In this structure, branch_a, branch_b, and ... represent dynamic keys. How can this be properly declared in typescript? Here is an attempt: ty ...

How can I effectively test a method within a React component using Jest and Typescript?

When working on .tsx components using Typescript and React, I want to write unit tests for the methods within my React component. For example: export default class SomeComponent extends React.Component<undefined, SomeComponentState> { someMetho ...

Surprising Media Component Found in URL Parameters within the design

Exploring the page structure of my Next.js project: events/[eventId] Within the events directory, I have a layout that is shared between both the main events page and the individual event pages(events/[eventId]). The layout includes a simple video backgro ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

Show an Angular Mat Card beneath the Input Field and position it on top of all other div elements

I am designing a signup page and I need to include a material card below the password field with checkboxes for password requirements. The challenge is that when the card appears, it pushes down all other elements such as the sign-up button. I want the ca ...

Learn how to efficiently read a Json file in Scala in order to access all fields as key value pairs, similar to how you would do so in a

Having trouble accessing all elements of the resultant map structure when reading a Json file in Scala using Jackson. Need help with Jackson JSON parsing Received output: Object = List(Map(source -> Map(name -> SSN, type -> String), target -> ...