trynacode trynacode - 3 months ago 8
Javascript Question

Parsing JSON in JavaScript using a variable

Was looking online for some help on this but couldn't find quite what I was looking for. I know how to parse a JavaScript variable, however, let's say I have the following JSON

{
"CPU INFO": {
"cpu0": "val",
"cpu1": "someval"
}
}


Let's assume I don't know how many CPUs there are and I want to set keys of a dictionary to the values. For example, if I had a loop such as:

for(var counterCPUS = 0; counterCPUS < numCPUs; counterCPUS++)
{
var currCPU = "cpu"+counterCPUS;
dictionary["cpu"+counterCPUS] = furtherCPUObject.currCPU;
}


Obviously this would not work since it would look for a String "currCPU", not "cpu0". How can I do what I am trying to achieve, assuming it is possible.

Thanks!

Answer

You can iterate objects using for..in and for..of, or you can get the object's keys as an array by using Object.keys and iterate over that:

var json = {
  "CPU INFO": {
    "cpu0": "val",
    "cpu1": "someval"
  }
};

for (var cpuKey in json['CPU INFO']) {
   console.log(cpuKey, '=>', json['CPU INFO'][cpuKey]);
}
               
Object.keys(json['CPU INFO']).forEach(function(key) {
   console.log(key, '=>', json['CPU INFO'][key]);       
});