[英]JS - JSON Parsing one has many
我找不到任何类似的问题,如果这与另一个相似,请原谅。 我有一个具有以下结构的JSON:
{
"data":[
{
"autores": { "autor": "Sérgio Pacheco Neves" }
},
{
"autores": {
"autor": [
"Julia Barbosa Curto",
"Roberta Mary Vidotti",
"Richard J. Blakely",
"Reinhardt Adolfo"
]
}
}
]
}
我想将每个“导师”作为个人记录并将其推入数组。 如您所见,它有时具有1,有时具有n个值的数组。 这必须使用javascript(jquery)实现。 我尝试了这个:
var autores = [];
$.each(contentData, function(i, v) {
$.each(this.autores, function(j, w) {
autores.push(w);
});
});
console.log(autores);
但是我没有遍历autores中的每个导师,而是得到了这个:
0: "Sérgio Pacheco Neves"
1: Array[4]
0: "Julia Barbosa Curto"
1: "Roberta Mary Vidotti"
2: "Richard J. Blakely"
3: "Reinhardt Adolfo"
我希望实现以下目标:
0: "Sérgio Pacheco Neves"
1: "Julia Barbosa Curto"
2: "Roberta Mary Vidotti"
3: "Richard J. Blakely"
4: "Reinhardt Adolfo"
我怎样才能做到这一点?
使用现有结构而不更改它,您可以通过检查所访问的条目是否为数组,如果是,则将其全部推入autores来autores
:
var autores = [];
$.each(contentData, function(i, v) {
$.each(this.autores, function(j, w) {
if (typeof w === "object") { // That's what it says for arrays
autores.push.apply(autores, w); // Push all of w's entries
} else {
autores.push(w);
}
});
});
console.log(autores);
但是正如我在评论中所说,我将修改结构,以便它始终为autor
返回一个数组,即使它只有一个条目也是如此。
检查您接收的数据类型,将字符串直接添加到数组中,否则,如果数据是数组,则将其连接到现有数组。
var autores = [];
$.each(contentData, function(i, v) {
$.each(this.autores, function(j, w) {
if(typeof w === "string")
autores.push(w);
else
autores = autores.concat(w)
});
});
console.log(autores);
这是区分大小写并填充数组的第三种方法:
var autores = [];
$.each(contentData, function(i, v) {
$.each(this.autores, function(j, w) {
if (w instanceof Array) {
$.merge(autores, w);
} else if (typeof w === "string") {
autores.push(w);
}
});
});
console.log(autores);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.