Javascript访问嵌套元素

时间:2014-11-26 12:45:10

标签: javascript arrays nested multi-level

我有一个看起来像这样的数组:

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

我希望得到 akch_faulted 的价值,但我无法弄明白。

我试过了:

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"

其中hardware.config()是我运行以获取结果数组的命令。

我只能像akch_chassis一样深......

有人能帮助我吗?

3 个答案:

答案 0 :(得分:2)

首先,result不是数组,是一个对象。

问题是你的嵌套对象在数组内部,所以要访问属性 akch_faulted ,你需要写这个:

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

答案 1 :(得分:1)

这是获取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>

答案 2 :(得分:0)

这可能会有所帮助,

  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;
     }
    }