gpt4 book ai didi

javascript - 在 Javascript 中遍历 JSON 对象?

转载 作者:行者123 更新时间:2023-11-30 05:45:01 26 4
gpt4 key购买 nike

下面是我的代码。请帮我遍历它。我想循环完整的 JSON 并进行一些验证,但我无法循环遍历它。我是第一次这样做,如果有人能帮助我,那就太好了。

有没有办法过滤JSON对象。例如,我想搜索 auditor1 asgn 值。过滤器可以是动态的,就像它可以是 auditor1 或 auditor11。我也想知道如何将上面的 json 转换为数组。这将使我的搜索变得容易(以防无法通过直接 JSON 搜索进行搜索)。

function fnMultiRowValidation(){
var vStatus = 5,
vJson = '{"tpaCo":[{"name":"Audit Company1",\
"aud":[{"name":"auditor1","asgn":"1","fnds":"1","lead":"1"},\
{"name":"auditor2","asgn":"1","fnds":"0","lead":"1"},\
{"name":"auditor3","asgn":"0","fnds":"1","lead":"0"},\
{"name":"auditor4","asgn":"1","fnds":"1","lead":"0"},\
{"name":"auditor5","asgn":"1","fnds":"1","lead":"0"},\
{"name":"auditor6","asgn":"0","fnds":"1","lead":"0"},\
{"name":"auditor7","asgn":"1","fnds":"1","lead":"0"},\
{"name":"auditor8","asgn":"1","fnds":"1","lead":"0"},\
{"name":"auditor9","asgn":"0","fnds":"1","lead":"0"},\
{"name":"auditor10","asgn":"1","fnds":"1","lead":"0"},\
{"name":"auditor11","asgn":"1","fnds":"1","lead":"0"}]},\
{"name":"Audit Company2",\
"aud":[{"name":"auditor3","asgn":"1","fnds":"1","lead":"1"},\
{"name":"auditor4","asgn":"1","fnds":"1","lead":"0"}\
]\
}\
]}';
var vObj = JSON.parse(vJson);


for (var i=0;i<vObj.tpaCo.length;i++){
$.each(vObj.tpaCo[i], function(key, value) {
console.log(key +':'+ value);
if(typeof(value)=='object'){
//console.log('Auditor length:'+vObj.tpaCo.value.length);
}
});
}
}

最佳答案

vObj.tpaCo.value.length

不会工作。您必须使用 vObj.tpaCo[key].lengthvalue.length。对于初学者,您不应将原生 for 循环与 each 迭代混合使用。

使用 for - 和 for-in -循环:

for (var i=0; i<vObj.tpaCo.length; i++) { // iterate through outer array
for (var key in vObj.tpaCo[i]) { // enumerate item keys
console.log(key +':'+ vObj.tpaCo[i][key]); // logs "name" and "aud"
}
console.log('Auditor length:'+vObj.tpaCo[i].aud.length);
for (var j=0; j<vObj.tpaCo[i].aud.length; j++) { // iterate "aud" array
console.log(vObj.tpaCo[i].aud[j].name);
}
}

通过使用变量简化:

var tpacos = vObj.tpaCo;
for (var i=0; i<tpacos.length; i++) {
var comp = tpacos[i];
for (var key in comp) {
var value = comp[key];
console.log(key +':'+ value);
}
var auds = comp.aud;
console.log('Auditor length:'+auds.length);
for (var j=0; j<auds.length; j++) {
var aud = auds[j];
console.log(aud.name);
}
}

现在有了 Array forEach method :

vObj.tpaCo.forEach(function(comp, i) {
for (var key in comp) {
var value = comp[key];
console.log(key +':'+ value);
}
console.log('Auditor length:'+comp.aud.length);
comp.aud.forEach(function(aud, j) {
console.log(aud.name);
});
});

还有jQuery's each :

$.each(vObj.tpaCo, function(i, comp) {
$.each(comp, function(key, value) {
console.log(key +':'+ value);
});
console.log('Auditor length:'+comp.aud.length);
$.each(comp.aud, function(j, aud) {
console.log(aud.name);
});
});

关于javascript - 在 Javascript 中遍历 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18461922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com