0

So I am using nodejs to send a get request to the vultr api which returns a nested json response that looks like this once I parse it:

Note: The first value '36539496' (and also the second value '36539499') is a dynamically created value that represents/matches the SUBID of that specific server, I have no way of knowing this value so I can't do anything like console.log(jsonParsed.36539496.main_ip)

 {
   '36539496' : {
    SUBID: '36539496',
    os: 'Ubuntu 16.04 x64',
    ram: '2048 MB',
    disk: 'Virtual 55 GB',
    main_ip: '123.456.789.10',
    vcpu_count: '1'
  },
  '36539499': {
    SUBID: '36539499',
    os: 'Ubuntu 16.04 x64',
    ram: '2048 MB',
    disk: 'Virtual 55 GB',
    main_ip: '123.456.789.10',
    vcpu_count: '1'
  }
}

I am trying to access the main_ip attribute for each server in the object but I can't seem to do it properly

I have tried using the bracket notation to access it that I have seen around this forum in order to access it, but for some reason using any object notation in general is giving me undefined errors, I am not sure if that is because I am doing the object notation wrong since the dynamic object is throwing me off. Any help is appreciated

1 Answers1

0

With Object.keys, you will get back an array of the keys. Then you can map over them to extract the main_ip field:

const obj = {
   '36539496' : {
    SUBID: '36539496',
    os: 'Ubuntu 16.04 x64',
    ram: '2048 MB',
    disk: 'Virtual 55 GB',
    main_ip: '123.456.789.10',
    vcpu_count: '1'
  },
  '36539499': {
    SUBID: '36539499',
    os: 'Ubuntu 16.04 x64',
    ram: '2048 MB',
    disk: 'Virtual 55 GB',
    main_ip: '123.456.789.10',
    vcpu_count: '1'
  }
};
console.log(Object.keys(obj).map(x => obj[x].main_ip));

If you run it, it should print

[
  "123.456.789.10",
  "123.456.789.10"
]
Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239