Reputation: 123
I need to access the following JSON and have to create check boxes based on number of books in each "options" array in "contents". If i access "ctrl.content = result.data.bookHistory.contents[0].options;" it is reading options array of contents[0] and check boxes are created successfully.In my case two check boxes has been created for two books Predator and Alien. But when i try "ctrl.content = result.data.bookHistory.contents[1].options.action;" no check boxes are created and ctrl.content shows undefined in "console.log(ctrl.content);" . I tried accessing "ctrl.content = result.data.bookHistory.contents[1].options;" also. No luck. Any help would be much appreciated.
JSON
{
"bookhistory" : {
"contents" : [
{
"options" : [
{
"title" : "Predator",
"type" : "CHECKBOX"
},
{
"title" : "Alien",
"type" : "CHECKBOX"
}]
},
{
"options" : [
{
"action" :
{
"title" : "batman",
"type" : "CHECKBOX"
}
}]
}]
}
}
Upvotes: 1
Views: 52
Reputation: 9095
options is an array you can't directly call options.action, you need to call options[0].action then it will give you the action object having the title and type.
Please see the below code.
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)
}
})
})
Upvotes: 1