简体   繁体   English

遍历JSON键和值

[英]looping through JSON Keys and values

it seems quite simple but some how i can't loop through the items as i would like to 似乎很简单,但是有些我无法像我想的那样遍历所有项目

i have this json object 我有这个json对象

"meters":{  
      "Rozvadec M11":{  
         "0":{  
            "Name":"m11-mcu13_sm114",
            "Title":"Svarovaci centrum Flexarc",
            "Parent":"m11-mcu13",
            "Status":"Running",
            "State":false
         },
         "1":{  
            "Name":"m11-mcu13_sm115",
            "Title":"Brousici centrum Solicad",
            "Parent":"m11-mcu13",
            "Status":"Running",
            "State":false
         }
      },
      "Rozvadec R1-L":{  
         "0":{  
            "Name":"r1-l-mcu1_sm100",
            "Title":"Amada NCT1",
            "Parent":"r1-l-mcu1",
            "Status":"Device unavailable",
            "State":false
         },
         "1":{  
            "Name":"r1-l-mcu1_sm101",
            "Title":"Amada 1",
            "Parent":"r1-l-mcu1",
            "Status":"Device unavailable",
            "State":false
         },
         "2":{  
            "Name":"r1-l-mcu1_sm102",
            "Title":"Amada 2",
            "Parent":"r1-l-mcu1",
            "Status":"Device unavailable",
            "State":false
         }
      },

what i am trying to do is to loop through all meters to have a list of 我想做的是遍历所有仪表以获取清单

"Rozvadec M11"
"Rozvadec R1-L"

and under each have a list of different smartmeters names 在每个下方都有一个不同的智能电表名称列表

i have this in ts 我在ts中有这个

let list =  this.http.get('EndpointURL');
         list.subscribe (
           (response: Response)=> 
           {this.meters.push(response);
           console.log(this.meters);
         })

and this in html (i was trying to loop only through the meters first before i nest the for loops) 和在html中的代码(我在嵌套for循环之前先尝试仅通过仪表循环)

<ul *ngFor="let meter of meters">
    <li>{{ meter}}</li>
</ul>

You have most of your code right but the ngFor is not used in that way. 您拥有大部分代码,但是ngFor并未以这种方式使用。 The html tag with the ngFor is what will be repeated and you that's why you should use it in the li instead of the list tag ul . 带有ngFor的html标签将重复出现,这就是为什么您应该在li使用它而不是list标签ul It would be like this for you: 对于您来说将是这样的:

<ul>
    <li *ngFor="let meter of meters">
        {{meter}}
    </li>
<ul>

This exact example is covered here in the docs . 在docs中涵盖这个确切的示例。

EDIT: If you want to access the key of your list, in this SO answer you can see the new way in Angular6 to retrieve it. 编辑:如果您想访问列表的键,在此SO答案中,您可以在Angular6中看到检索它的新方法。 It will end up like this for your example: 对于您的示例,最终将像这样:

<ul>
    <li *ngFor="let meter of meters | keyvalue">
        {{meter.key}}
    </li>
<ul>

You can read more about the keyValuePipe in the docs . 您可以在docs中阅读有关keyValuePipe更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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