Instructions on how to extract and display the key-value pairs from a nested JSON array in Angular 2, then populate them in a select box

My goal is to extract data from a Json data model and populate a select box with the data as drop-down items. However, I am encountering difficulties in achieving this as the entire Json array is being printed instead of just the 3 major headings that I want.

Error Message:-ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Below are my sample Json data and the expected output:

Expected Output

LEED V4 BD+C LEED V4 ID+C LEED V4 EBOM

Sample Json Data

{
    "Ratings": {
        "LEED V4 BD+C": [{

        }],
        "LEED V4 ID+C": [{

        }],
        "LEED V4 EBOM": [{

        }]
    }
}

app.ts

 template: `
            <div class="col-md-6 form-group">
               <label class="control-label">Rating System <span style="color: #2196f3;">*</span></label>
                <select class="form-control" id="productparameter" *ngFor="let item of ratings.Ratings" >
                <option value="">Select Rating</option>
                <option value="">{{item}}</option>
              </select>
              </div>
  `,
})

export class App {
 public ratings: any ={
    "Ratings": {
        "LEED V4 BD+C": [{

        }],
        "LEED V4 ID+C": [{

        }],
        "LEED V4 EBOM": [{

        }]
    }
}
  constructor( ) {

    console.log( this.ratings.Ratings);

  }

Here is the link to my Plunker project for further reference:https://plnkr.co/edit/pgbeS9iRkAzgWVNrLNQJ?p=preview

Answer №1

To begin, ensure that you are using the ngFor directive within your option tag rather than the select element itself.

<select class="form-control" id="productparameter"  >
   <option value="">Select Rating</option>
   <option *ngFor="let item of elements" value="">{{item}}</option>
</select>

In your component model, create an array to store all possible keys from this.ratings.Ratings.

public elements: any = Object.keys(this.ratings.Ratings);

Utilize this newly created array in your ngFor directive like so:

*ngFor="let item of elements"

You can view the updated Plunkr here.

Answer №2

I'm having trouble understanding the desired display, but I attempted the following:

// Root component of our app
import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

@Component({
   selector: 'my-app',
   template: `
        <div class="col-md-6 form-group">
           <label class="control-label">Rating System <span style="color: #2196f3;">*</span></label>
            <select class="form-control" id="productparameter">
            <option value="">Select Rating</option>
            <option value="" *ngFor="let rat of rating">{{rat}}</option>
          </select>
          </div>`,
})

export class App {
     public rating: any = ["LEED V4 BD+C": ["One"], "LEED V4 ID+C": ["Two"], "LEED V4 EBOM": ["Three"]];
    
    constructor() {}

}

@NgModule({
   imports: [BrowserModule, FormsModule],
   declarations: [App],
   bootstrap: [App]
})
export class AppModule {}

The expected output is shown below:

https://i.sstatic.net/U9y2h.png

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

Tips for implementing a 301 redirect on an AngularJS website

Our AngularJS website has a requirement where we need to implement a 301 redirect. For instance, if a user accesses page "A" at mysite.com/A, we want to redirect them to mysite.A.com. We are seeking advice on the best approach to handling this situation. ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...

"Learn the best way to showcase images within Pusher's real-time chat application

Having trouble displaying images in real-time chat using Pusher. I am storing the images as BLOB but cannot display them on the client side using JavaScript. When the person who sends the message types, the image shows up fine, but on the receiver's s ...

Instructions on utilizing the transpiled "main.js" file using gulp

As a novice in Angularjs 1.0, I encountered issues with my script and decided to use gulp to compile ec6 to ec5 by implementing the code provided below. The compilation process generated the file main.js. However, I am unsure about how to connect it when l ...

Bootstrap Dropdown Functionality Malfunctioning

Here is a simple piece of HTML code that I have created: <!doctype html> <html> <head> <meta charset="utf-8"> <title>.:Home Page:. The Indian Sentinel</title> <link rel="stylesheet" href=" ...

Sending an array of data using Angular in a web service

Here is my model object from model.ts name_id: string[]; public generateUrlencodedParameters(token: string, id?: number): string { let urlSearchParams = new URLSearchParams(); urlSearchParams.append('name_id', this.name_id.toS ...

Learn how to change the icon in Vuejs when the class 'active' is present

I have a bottom navigation bar with icons. How can I make it so that when the router-link has the class 'active', the icon associated with it also becomes active? By default, the first icon is active. <li> <router-link v-if="ac ...

Show only the lower left quadrant within the img tag during the prepend operation

I'm attempting to add an <img> tag in front of a <div> similar to this example on JSFiddle. However, I have a specific requirement to only display the bottom left quarter of the image instead of the entire one. HTML Markup <div id="my ...

What is the best way to confirm checkbox selection based on MySQL data?

Writing this question feels challenging, but I have a collection of checkboxes with their data stored as JSON in my PHP database. What I'm trying to achieve now is to dynamically load the JSON data on the page without refreshing it, checking specific ...

Unable to display items in controller with AngularJS

I am facing an issue with displaying a slider using ng-repeat in my AngularJS code. The pictures and other elements defined in the controller are not showing up on the page. Here is the JavaScript code snippet: angular.module('starter', []) .co ...

Refreshing the page triggers a 404 error, indicating that the parameter is being passed as a template

Encountering difficulties with my angular routes when a page is refreshed by a user or accessed directly through the browser, rather than navigating via internal links on the site. thing.js - an angular factory .factory( 'Things', ['$resou ...

What are the steps for changing this JavaScript file into TypeScript?

I'm currently in the process of converting this JavaScript file to TypeScript. However, I've encountered an error with the onClick function as shown below: import React from 'react'; import { Popover } from 'antd'; import A fr ...

What is the process of using a For loop to output a string in reverse order?

I'm attempting to reverse the string "hello" using a For loop, aiming for the output of "olleh". However, I'm facing an issue where the last character in the string is not being removed after being added to the array. Consequently, only the last ...

What is the best way to include a JavaScript variable within CSS styling?

I am currently implementing a dropdown menu system where the image of a parent div changes on mouse hover over a link, and reverts back when the mouse moves away. I have this functionality set up using a variable in my HTML code. Is there a way for me to m ...

Unable to merge with my personalized string class

I have been working on creating my own custom string class and I am almost done. However, I encountered an issue where the program did not provide the expected output. Here are the details: Input: string a = "Hello" string b = "World!" Expected output: ...

Can anyone assist in reviewing this json string array in vb.net?

{"images":[{"id":"obj_0","src":"background.jpg","width":"640","height":"480"},{"id":"obj_9","src":"elements/pipe.png","width":50,"height":44,"top":196,"left":154,"rotation":"0"},{"id":"obj_13","src":"elements/cigarette.png","width":45,"height":67,"top":168 ...

Does AngularJS's scope.$apply function operate synchronously?

Can you confirm if this code is synchronous in AngularJS? scope.$apply(function(){ console.log('foo'); }); ...

Integrating additional information (HTML) into current content utilizing Vue JS data structures

I am attempting to use Vue JS to load content onto a page. The user interface consists of a select element, a textarea, and a button. I want to display data from a third-party API response on the page. The first item loads successfully, but subsequent item ...

Sort and categorize JSON data with JavaScript/jQuery using group by and order by

Having some JSON data, I am looking to group by and sort the author names in alphanumeric order. Previously asked this question with no satisfactory answer, so this time I will provide more details. Can someone explain the difference between groupby and o ...

How can you isolate the date portion from a DateTime Object using JavaScript?

My array is currently working fine, but I need to reorganize it groupwise by DateWise: [ { name: 'Ali', startedAt: Wed Dec 28 2016 15:32:07 GMT+0500 (Pakistan Standard Time), userId: '0002' }, { completedAt: Wed D ...