Phoebe Phoebe - 22 days ago 11
Javascript Question

Evaluating key values in multi-dimensional object

I have a multi-dimensional object that looks like this:

{
"links": [{"source":"58","target":"john","total":"95"},
{"source":"60","target":"mark","total":"80"}],
"nodes":
[{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
}


I am trying to evaluate the value of "total" in "links." I can do this in a one-dimensional array, like this:

for (var i = 0; i < data.length; i++) {
for (var key in data[i]) {
if (!isNaN(data[i][key])) {
data[i][key] = +data[i][key];
}
}
};


But I have not been able to figure out how to do this in two-dimensions (especially calling the value of key "total" by name).

Can anybody set me on the right track? Thank you!

Answer

Starting from the principle that the structure of your array is this, you can to iterate the keys and the values:

var obj = {
 "links": [{"source":"58","target":"john","total":"95"},
           {"source":"60","target":"mark","total":"80"}],
 "nodes": 
          [{"name":"john"}, {"name":"mark"}, {"name":"rose"}]
};

for (var key in obj){
  obj[key].forEach(function(item){
    for(var subkey in item){
      if (subkey == 'total')
        console.log(item[subkey]);
    };
  });
};