首页 > 解决方案 > ngFor 在打字稿中的嵌套地图

问题描述

我想遍历嵌套映射以从第二个映射的列表中获取值。

地图:

public groupedItemMap: Map<string, Map<string, ItemSearchResult[]>>;

地图结构:

Map
--[[Entries]]
----0
-------key - number (if occured once or is duplicate)
-------value - Map
---------[[Entries]]
-----------key - itemNumber
-----------value - List of object(s) with parameters 'id',..'name' and so on and same itemNumber

++++++++++++if itemNumber is different there are more objects of the same type with different itemNumber
-----------key
-----------value

我想从中访问对象列表。

  <!-- Here keyvalue is not possible on groupedItemMap -->
<div *ngFor="let group of groupedItemMap.entries()">   
    <span>{{ group.key }}</span>
    <div *ngFor="let items of group| keyvalue">
        <span>{{ items.key }}</span>
        <div *ngFor="let item of items.value">
            <span>{{ item.id }}</span>
        </div>
    </div>
</div>

如果我不使用它keyvaluegroupedItemMap我只能通过 4 个*ngFor循环访问它,并且map.entries()循环我的 html 标记中的所有项目。

地图

标签: angulartypescriptfor-loopmultidimensional-arrayhashmap

解决方案


您可能需要同时使用keyvalue这两个循环。尝试以下

<li class="list-group-item" *ngFor="let first of groupedItemMap">
 <div *ngFor="let second of first | keyvalue">
   <div *ngFor="let item of second.value | keyvalue">
     <!-- Here `item.value` is an array. So you possibly need another *ngFor. Test with `json` pipe -->
     <strong innerHTML="{{ item.key }} x {{ item.value | highlight: highlight }}">
     </strong>
     <span class="text-description margin-bottom-5"
         innerHTML="{{ 'number' | translate }}: {{ item.number|highlight:highlight }}"></span>
   </div>
 </div>

推荐阅读