如何使用angular和Typescript获取多个数组中的对象值?

问题描述

我需要帮助来获取总数组中每个数组的项目和颜色值

这是我的json的示例

 "results ": {
"totals": {
  "total": [
    {
      "item": "car","color": "red"
    },{
      "item": "car","color": "white"
    },{
      "item": "bike","color": "green"
    }
  ]
},

这是我用来从json响应中获取项目和颜色的打字稿代码

  let i = 0;
         this .items = response.results.totals.total.forEach((x)=>
              {
                this .item = x.item ;
                this .color = x.color;
               i++
              }
          

HTML

 <pre><strong>Item</strong>{{item}}</pre>
  <pre><strong>Color</strong>{{color}}</pre>

运行代码时,我只能显示总数组中的第一个数组

Items : car 
Color: red

如何获取总数组中的所有值并使用html显示页面中,这样我的输出看起来像这样?

Items : car
Color: red
Items : car
Color: white
Items : bike
Color: green 

解决方法

this.items = response.results.totals.total;

this.items设置为要显示的项目的数组。

并使用ngFor以html显示项目:

<div *ngFor="let item of items">
  <pre><strong>Item</strong>{{item.item}}</pre>
  <pre><strong>Color</strong>{{item.color}}</pre>
</div>