Javascript accessing nested elements

54 views Asked by At

I have an array that kind of looks like this:

result = {
   akch_generation: 11841,
   akch_chassis: [{
    akch_sp: [{
        akch_faulted: false,
        akch_present: true,
        akch_fru: 'hc:///chassis=0/sp=0'
    }],
    akch_fan: [{
   ....
 }

And I want to get to the value of akch_faulted, but I can't figure out how.

I tried:

hardware.config().akch_chassis.akch_sp => result = undefined

hardware.config().akch_chassis.akch_sp.akch_faulted =>
error: illegal argument expression: "hardware.config().akch_chassis.akch_sp has
   no properties"

where hardware.config() is the command I run to get the result array.

I can only get as deep as akch_chassis...

Can anybody help me?

3

There are 3 answers

6
ianaya89 On BEST ANSWER

First of all result is not an array, is an object.

The problem is that yours nested objects are inside arrays so to access the property akch_faulted you need to write this:

result.akch_chassis[0].akch_sp[0].akch_faulted
0
AishwaryaVengadesan On

This may be helpfull,

  for(var i=0;i<=result.akch_chassis.length;i++){
     for(var j=0;j<=result.akch_chassis[i].akch_sp.length;j++){
       var value=result.akch_chassis[i].akch_sp[j].akch_faulted;
     }
    }
1
Saajan On

This is the solution to get the value in javascript .

var myvalue = result.akch_chassis[0].akch_sp[0].akch_faulted

<script type="text/javascript" language="javascript" src="my.json"></script>
<script>
window.onload = function(){
var myvalue = result.akch_chassis[0].akch_sp[0].akch_faulted;
console.log(myvalue);
    }
</script>