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']);
               })


  })
}
1
  • 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. Commented Feb 10, 2016 at 12:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

really value, key but what I want is just bdev0 and bdev1 just these names first so that I can push them to a dropdown
access that names as key in callback
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.

1 Comment

you cannot use object.keys in angular directly according to this answer stackoverflow.com/questions/25299436/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.