简体   繁体   中英

Looping through a JavaScript array

I have the following Array

categories = [{"id_product_cat":1,"category":"food","id_product_sub_cat":1,"subcategory":"Pizza"},{"id_product_cat":1,"category":"food","id_product_sub_cat":2,"subcategory":"Burger"},{"id_product_cat":1,"category":"food","id_product_sub_cat":3,"subcategory":"Chicken"},{"id_product_cat":1,"category":"food","id_product_sub_cat":4,"subcategory":"Sandwiches"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":5,"subcategory":"Beer"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":6,"subcategory":"Wine"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":7,"subcategory":"Liquor"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":8,"subcategory":"Water"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":9,"subcategory":"Juice"}]

And I would like to loop through this preferably using a forEach() loop statement to reproduce the following in Angular. Category Name as heading then the respective sub-categories under each Category.

<div class="col-sm-12 vertical-menu">
       <h5>Categories</h5>
       <div class="vert-menu-list">
         <h6>Food</h6>
        <ul>
            <li><a routerLink="/">Burgers</a> </li>
            <li><a routerLink="/">Chicken</a></li>
            <li><a routerLink="/">Pizzas</a></li>
            <li><a routerLink="/">Sandwich</a></li>
        </ul>

        <h6>Drinks</h6>
        <ul>
            <li><a routerLink="/">Beer</a> </li>
            <li><a routerLink="/">Wine</a></li>
            <li><a routerLink="/">Liquor</a></li>
            <li><a routerLink="/">Water</a></li>
            <li><a routerLink="/">Juice</a></li>
        </ul>
       </div>
       
    </div> 

You can use ng-for , but before that you need to restructure the categories to have the following structure.

const categories = 
  [
    {
      category: "something", 
      subcategory: [
        {
          to:"somewhere", 
          label:"someString"
        }
      ]
    }
  ];
<div class="col-sm-12 vertical-menu">
       <h5>Categories</h5>
       <div class="vert-menu-list" *ngFor="category in categories">
         <h6>{{category.category}}</h6>
         <ul *ngIf="category.subcategory">
            <li *ngFor="subLink in category.subcategory">
              <a [routerLink]="subLink.to">
                {{subLink.label}}
              </a>
            </li>
         </ul>
       </div>
    </div> 

You can do for loop in angular like this

<div *ngFor="let item of items; let myIndex = index>
  {{myIndex}}
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM