texi rv texi rv - 6 months ago 9
CSS Question

printing json values inside array using js

I am trying to print the football value which is inside array using JS. I am not sure how to print it in JS. Right now when I try it prints as

undefined
. I am providing part of my JS and JSON below, can you guys tell me how to fix it?

if (item.data.football == true) {
console.log("print football---->" + item.data[0].football);
}


"data": [{
"sportsProperty": "Insurance",
"football": true
},
{
"sportsProperty": "Insurance",
"football": true
}]

Answer

The data property of your object is an array, so you need to access its members by index. Try this:

if (item.data[0].football) { // note the [0] after 'data'
    // do something...
    console.log(item.data[0]);
}

The above will only access the first item in the array. If you want to work with all of them you need to use a loop, like this:

for (var i = 0; i < item.data.length; i++) {
    if (item.data[i].football) {
        // do something...
        console.log(item.data[i]);
    }
}

Working example