我需要访问以下JSON,并且必须根据“目录”中每个“选项”数组中的书籍数量创建复选框。如果我访问“ ctrl.content = result.data.bookHistory.contents [0] .options;”它正在读取options [0]的内容数组,并成功创建了复选框。在我的情况下,已经为两本书Predator和Alien创建了两个复选框。但是当我尝试“ ctrl.content = result.data.bookHistory.contents [1] .options.action;”时没有创建复选框,并且ctrl.content在“ console.log(ctrl.content);”中显示未定义。我尝试访问“ ctrl.content = result.data.bookHistory.contents [1] .options;”也。没运气。任何帮助将不胜感激。
JSON
{
"bookhistory" : {
"contents" : [
{
"options" : [
{
"title" : "Predator",
"type" : "CHECKBOX"
},
{
"title" : "Alien",
"type" : "CHECKBOX"
}]
},
{
"options" : [
{
"action" :
{
"title" : "batman",
"type" : "CHECKBOX"
}
}]
}]
}
}
答案 0 :(得分:1)
options是一个不能直接调用options.action的数组,您需要调用options [0] .action然后它会为您提供具有标题和类型的action对象。
请参见下面的代码。
var res = {
"bookhistory" : {
"contents" : [
{
"options" : [
{
"title" : "Predator",
"type" : "CHECKBOX"
},
{
"title" : "Alien",
"type" : "CHECKBOX"
}]
},
{
"options" : [
{
"action" :
{
"title" : "batman",
"type" : "CHECKBOX"
}
}]
}]
}
}
console.log("direclty calling =>",res.bookhistory.contents[1].options[0].action)
// you can use the forEach method, you can check the data basically contents is an array and for the first item options doesn't have action but the second item in the contents have action for the options array.
// inorder to print you can use a if conditon as shown below
console.log("using loops")
res.bookhistory.contents.forEach(o => {
o.options.forEach(so => {
if(so.action){
console.log(so.action)
}else{
console.log(so)
}
})
})