简体   繁体   English

如何在Angular中获取JSON对象的名称

[英]How to get names of json object in angular

I have a data set 我有一个数据集

$scope.mydata = [{
    "Block_Devices": {
      "bdev0": {
        "Backend_Device_Path": "/dev/ram1",
        "Capacity": "16777216",
        "Bytes_Written": 1577,
        "timestamp": "4365093970",
        "IO_Operations": 17757,
        "Guest_Device_Name": "vdb",
        "Bytes_Read": 17793,
        "Guest_IP_Address": "192.168.26.88"
      },
      "bdev1": {
        "Backend_Device_Path": "/dev/ram2",
        "Capacity": "16777216",
        "Bytes_Written": 1975,
        "timestamp": "9365093970",
        "IO_Operations": 21380,
        "Guest_Device_Name": "vdb",
        "Bytes_Read": 20424,
        "Guest_IP_Address": "192.168.26.100"
      }
    },
    "Number of Devices": 2
  }]

and I would like to create a array from this json such as 我想从这个json创建一个数组,例如

devices = ['bdev0', 'bdev1']

when I try 当我尝试

$scope.mydata.Block_Devices it gives me the whole json object but I just want the names of the objects ie bdev0 and bdev1 how can I get that? $scope.mydata.Block_Devices它给了我整个json对象,但是我只想要对象的名称,即bdev0和bdev1我怎么能得到呢?

Try this: 尝试这个:

var devices = [];

for (var key in $scope.mydata[0].Block_Devices) {
    devices.push(key) 
}

万一ES5解决方案

devices = Object.keys($scope.mydata[0].Block_Devices)

You have to loop through the object properties to archive this: 您必须遍历对象属性才能将其归档:

var devices = [];
var data = $scope.mydata[0].Block_Devices;

for (var name in data) {
  if (data.hasOwnProperty(name)) {
    devices.push(name);
  }
}

The hasOwnProperty call is important to skip the properties which are from prototype, if you are sure that there are none, you can skip this. hasOwnProperty调用对于跳过原型中的属性很重要,如果您确定没有属性,则可以跳过此属性。

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

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