2017-02-10 148 views
0

基本上我从php获取json格式的数据。我无法控制我得到的数据。样本输出是:通过此json数据循环访问数组子元素

var Data={"2":[{"name":"Mr Samuel","votes":"11"}],[{"name":"Mrs Clair Cher","votes":"2"}],"3":[{"name":"Mr Madiex","votes":"13"}]}; 

的数据是这样的:在一个部门,其ID为2,而Mr.Madiex工作在部门3票是他们得到的选票Mr.Samuel和夫人克莱尔工作他们的表现。现在我需要循环访问数据,获取名称和投票。

$.each(Data, function(departmentid, staffmembers){ 
//departmentid is well captured: 2 and 3. But I am having a hard time going thru each departments staff members: 

    $.each(Data[departmentid], function(index,value){ 
    //here, i expected that Data[departmentid][index].name would give me name but it is undefined. 
    }); 


}); 

我究竟错过了什么?

+0

“Data”赋值语法错误。请先解决这个问题,这样我们就可以确定你的JSON数据结构实际上是什么。 – trincot

+0

@trincot这就是我从php代码(我无法控制它)得到的。我确实问过后端开发者,但他并不是很帮忙。 var data = {“2”:[{“staffname”:“Samuel Andom先生”,“票数”:“11”},{“staffname”:“克莱尔夫人”,“票数”:“2”}] 3“:[{”staffname“:”Mr Madiex“,”votes“:”13“}]} –

+0

我刚刚尝试过,并且您的代码有效。 – trincot

回答

0

校正在原来的问题中的代码后,似乎工作(假设你已经包括jQuery的):

var Data = { 
 
    "2": [ 
 
     {"name":"Mr Samuel","votes":"11"}, 
 
     {"name":"Mrs Clair Cher","votes":"2"} 
 
    ], 
 
    "3": [ 
 
     {"name":"Mr Madiex","votes":"13"} 
 
    ] 
 
}; 
 

 
$.each(Data, function(departmentid, staffmembers){ 
 
    $.each(Data[departmentid], function(index,value){ 
 
     console.log(Data[departmentid][index].name); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

当然,你还不如用staffmembersvalue参数:

var Data = { 
 
    "2": [ 
 
     {"name":"Mr Samuel","votes":"11"}, 
 
     {"name":"Mrs Clair Cher","votes":"2"} 
 
    ], 
 
    "3": [ 
 
     {"name":"Mr Madiex","votes":"13"} 
 
    ] 
 
}; 
 

 
$.each(Data, function(departmentid, staffmembers){ 
 
    $.each(staffmembers, function(index,value){ 
 
     console.log(value.name); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

谢谢Trincot!精彩。 –