Search code examples
angularloopsobjectngfor

ngFor multidimensional json object


I have my angular application calling an external API which returns a JSON string of products.

The productService makes a simple API call:

getProducts() {
    return this.http.get(this.apiUrl + '/getProducts', this.config)
}

My component subscribes the data to a variable:

AllProducts: Object;
ProductGroups: Object;

constructor(private _product: ProductService) {}

ngOnInit() {
    this._product.getProducts().subscribe(data = > {
        this.AllProducts = data;
        this.ProductGroups = Object.keys(data);
        console.log("Got Products");
        console.log(this.AllProducts);
        console.log(this.ProductGroups);
    })
}

The Json string looks like:

{\"Product1\": {\"P1-1\": {\"productType\": \"Test\", \"productStatus\": \"In Stock\", \"productTitle\": \"Product1 Test Product\", \"productDescription\": \"First test product1\"}}, \"Product2\": {\"P2-1\": {\"productType\": \"Test\", \"productStatus\": \"In Stock\", \"productTitle\": \"Product2 test product 1\", \"productDescription\": \"The first product of group 2\"}, \"P2-2\": {\"productType\": \"Test\", \"productStatus\": \"Out of Stock\", \"productTitle\": \"Product2 test product 2\", \"productDescription\": \"Second product of group 2\"}}}

The Browser console output for AllProducts looks like:

Object {
Product1: Object {
"P1-1": Object { productType: "Test"
 ...

My HTML uses nested *ngFors to try and render anything on the page:

<div *ngfor='let productGroup of ProductGroups'>
   <h2>{{productGroup}}</h2>
   <ul>
      <li *ngfor="let item of AllProducts['productGroup']">
         {{item}}
      </li>
   </ul>
</div>

The <h2> renders the product group names correctly, but I have not been able to list any of the product details.

Edit:

I have control over the API as well if it is easier to tweak the JSON string.

I should also mention that it is currently on Angular 6.0.0 and I have not been able to get it to work on 6.1.0 or any other versions yet.


Solution

  • You can use KeyValuePipe (available in angular 6.1) for this:

    <div *ngFor='let productGroup of AllProducts | keyvalue'>
        <h2>{{productGroup.key}}</h2>
        <ul>
          <li *ngFor="let item of productGroup.value | keyvalue">
            {{item.key}}
             <ul>
                <li *ngFor="let innerItem of item.value | keyvalue">
                      {{innerItem.key}}: {{innerItem.value}}
                </li>
             </ul>
          </li>
        </ul>
      </div>