微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。