[英]Json Object fetch from javascript array
我有这样的 Json object
{
" resultArr": [
{
"ID":"1",
"0":"1",
"APPROVAL LEVEL":"1",
"1":"1",
"WorkFlow Type Code":"1",
"2":"1",
"Employee Number":"825489602V",
"3":"825489602V",
"Employee Name":"Wajira Wanigasekara",
"4":"Wajira Wanigasekara"
}
]
}
我正在尝试打印 resultArr 的键和值。
例如,我想像这样打印 ID=1 APPROVAL LEVEL=1..
我可以使用此代码获取 ID、APPROVAL LEVEL.. 的值
$.ajax({
type: "POST",
async:false,
url: "<?php echo url_for('workflow/getApprovalByModuleView') ?>",
data: { viewName: viewName },
dataType: "json",
success: function(data){
alert(data.resultArr[0][3]);
}
});
但我也想打印这些名字......
这意味着我想要打印 data.resultArr 数组的 KEY 和 VALUE
我怎样才能做到这一点?
好吧,您使用 select 值的密钥。 我能想到的唯一方法是循环遍历它们:
$.each(data.resultArr, function(index, value) {
alert(index + ': ' + value);
});
我很确定您作为成功参数获得的data
变量不是您所期望的。
首先,弄清楚数据实际包含什么。 我建议安装Firebug而不是警告编写:
console.dir(data);
还要检查数据类型尝试:
console.log(typeof(data));
现在您知道了数据真正返回的格式,您可以继续处理它。
var json = {"resultArr":[{"ID":"1","0":"1","APPROVAL LEVEL":"1","1":"1","WorkFlow Type Code":"1","2":"1","Employee Number":"825489602V","3":"825489602V","Employee Name":"Wajira Wanigasekara","4":"Wajira Wanigasekara"}]};
for(var key in json.resultArr[0]) {
console.log( key, json.resultArr[0][key] );
}
javascript:
var array = {"key" : "value", "anotherkey" : "anothervalue"};
for (key in array){
document.write("For the Element " + "<b>"+array[key]+"</b>"
+ " Key value is " +"<b>"+key+"</b>"+"<br>");
}
这将从 javascript 中的数组中获取键和值。
您遇到的问题是我认为您正在访问两个不同的数组对象。
data.resultArr[0][3]
与data.resultArr[0]["3"]
不同,后者与 data.resultArr[0]["Employee Number"] 不同. The first will give you the VALUE for
. The first will give you the VALUE for
批准级别the second will give the the SECOND employee number and the last will give you the value for
。
您可以使用以下代码:
var json = {"resultArr":[{"ID":"1","0":"1","APPROVAL LEVEL":"1","1":"1","WorkFlow Type Code":"1","2":"1","Employee Number":"825489602V","3":"825489602V","Employee Name":"Wajira Wanigasekara","4":"Wajira Wanigasekara"}]};
var data = json.resultArr[0];
for (var key in data){
document.write(key+":" + data[key]);
}
也许这有帮助:
function getArrayKeyAndValue(array, index){ var count = 0; for (key in array){ if(++count == index) return [key, array[key]]; } } var array = {"key1" : "value1", "key2" : "value2", "key3" : "value3"}; document.write(getArrayKeyAndValue(array, 1));
Output 是:“key1,value1”;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.