1

I have a JSON structure as follows

var myJson = {
   "Number of Devices":2,
   "Block Devices":{
      "bdev0":{
         "Backend_Device_Path":"/dev/ram1",
         "Capacity":"16777216",
         "Bytes_Written":9848,
         "timestamp":"4365093970",
         "IO_Operations":87204,
         "Guest_Device_Name":"vdb",
         "Bytes_Read":107619,
         "Guest_IP_Address":"192.168.26.88"
      },
      "bdev1":{
         "Backend_Device_Path":"/dev/ram2",
         "Capacity":"16777216",
         "Bytes_Written":10062,
         "timestamp":"9365093970",
         "IO_Operations":93789,
         "Guest_Device_Name":"vdb",
         "Bytes_Read":116524,
         "Guest_IP_Address":"192.168.26.100"
      }
   }
}

I want to select Block Devices that is bdev0, bdev1... and also their values normally this is easy to do using Object.keys in vanilla javascript but it seems that I cannot use this function in angular so I tried angular.forEach but It returns undefined.

here is how far I could go

function getData(){
  $http.get(path)
  .success(function(data){
    $scope.devices = data
    angular.forEach($scope.devices, function(item){
                   console.log(item['Block Devices']);
               })


  })
}
Imo
  • 1,455
  • 4
  • 28
  • 53
  • As an aside, that's not JSON, it's just an object (created via an object literal). JSON looks similar, but is a *string* representation (serialisation) of an object. – nnnnnn Feb 10 '16 at 12:23

2 Answers2

5

use forEach as in code snippet below to access desired properties:

angular.forEach($scope.devices['Block Devices'], function(value, key) {
   console.log(value, key);
   // Would log value of $scope.devices['Block Devices'][key]
   // and key name which is 'bdev0', 'bdev1' etc.
})

In that way you can access value of bdev0, bdev1 as value and name as of device as key in your callback function.

Valentin Podkamennyi
  • 7,161
  • 4
  • 29
  • 44
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
0

Angular is a javascript framework. Anything which works in vanilla javascript will work here also. About your question: you should iterate like this:

angular.forEach($scope.devices['Block Devices'], function(value, key){
       console.log(key);
})

This will console bdev0, bdev1 etc.

ashfaq.p
  • 5,379
  • 21
  • 35
  • you cannot use object.keys in angular directly according to this answer http://stackoverflow.com/questions/25299436/unable-to-call-object-keys-in-angularjs – Imo Feb 10 '16 at 12:41