如何在角度中获取json对象的名称

时间:2016-05-11 10:37:19

标签: javascript angularjs json

我有一个数据集

$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
  }]

我想从这个json创建一个数组,比如

devices = ['bdev0', 'bdev1']

当我尝试

$scope.mydata.Block_Devices它给了我整个json对象,但我只想要对象的名称,即bdev0和bdev1,我怎么能得到它?

3 个答案:

答案 0 :(得分:1)

试试这个:

var devices = [];

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

答案 1 :(得分:1)

以防万一ES5解决方案

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

答案 2 :(得分:0)

您必须遍历对象属性才能将其归档:

TwitterTopologyCreator topology = new TwitterTopologyCreator();    
topology.setSpout("kafka-spout1", new KafkaSpout(spoutConf1), 1); 
topology.setSpout("kafka-spout2", new KafkaSpout(spoutConf2), 1);
topology.createTopology(topologyName, clientName);

hasOwnProperty调用对于跳过原型属性很重要,如果你确定没有,你可以跳过它。