1

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
}]

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Are you declaring item? By writing item.data, you're implying that the data object lies within an item object. In order to work, your code should look something like the following:

var item = {
  "data": [
    {
      "sportsProperty": "Insurance",
      "football": true
    },
    {
      "sportsProperty": "Insurance",
      "football": true
    }
  ]
};

Also, item.data.football returns undefined, because you need to specify a location within the array. Otherwise, you can ask:

if (!!item.data)

Which will return true if item.data is not an empty object.

Let me know if you need any further help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.