基本上我从php获取json格式的数据。我无法控制我得到的数据。示例输出为:
var Data={"2":[{"name":"Mr Samuel","votes":"11"}],[{"name":"Mrs Clair Cher","votes":"2"}],"3":[{"name":"Mr Madiex","votes":"13"}]};
数据是这样的:萨穆埃尔先生和克莱尔夫人在一个身份为2的部门工作,而麦迪克斯先生在部门3工作。投票是他们为表现而获得的选票。现在我需要遍历数据,获取名称和投票。
$.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 :(得分: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>
当然,您也可以使用staffmembers
和value
参数:
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>