Dynamic object key to display *ngFor in Nativescript with Angular

Issue

I have the dataset which has derived from the group by product name as below. I need to iterate the array of object and display the product name with all the size of the product.

Sample dataset

   [ {
  "TEST 1": [
    {
      "content_id": "88282",
      "product_name": "TEST 1",
      "price": "36.00",
      "size" : "XL"
    },
    {
      "content_id": "88283",
      "product_name": "TEST 1",
      "price": "37.00",
      "size" : "XXL"
    }
  }],

{
  "TEST 2": [
    {
      "content_id": "882821",
      "product_name": "TEST 2",
      "price": "36.00",
      "size" : "XL"
    },
    {
      "content_id": "882832",
      "product_name": "TEST 2",
      "price": "37.00",
      "size" : "XXL"
    }]
]

I need to iterate the above result and need to display as Product name with all sizes such as “TEST 1 (XL XXL ) and TEST 2 (XL XXL)

What I am trying is

<—– need to display here ———>

Solution

You can use Object.keys() to get keys or use foreach() to iterate json.
E.g.

const object1 = {"data":
        [ {  "TEST 1": [    {
      "content_id": "88282",
      "product_name": "TEST 1",
      "price": "36.00",
      "size" : "XL"
    },    {
      "content_id": "88283",
      "product_name": "TEST 1",
      "price": "37.00",
      "size" : "XXL"
    }
  ]
}
]


};

object1[Object.keys(object1)[0]].forEach(function(element) {
  console.log(element);
});

Answered By – Narendra

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.