0

I have a sample JSON file:

{
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}

I need to get object from array. Everything work but I want to show alert that there is no "4" in that object

Tried something like that:

if(check == null){
    alert("not exist")
}

But its not working. I tried also put undefined instead of null but it is not working as well. What should i put there ?

Rest this are working fine. I know how to get data from JSON. The only issue is that check function.

                    $.getJSON(host_address ,function(data){
                        var check = data.array[4]
                        if(check == null){
                            alert("not exist")
                            }
                    });
user3347455
  • 51
  • 1
  • 8

2 Answers2

1

You can do this (I assume you have a usable JSON object you've fetched):

var data = {
  "array": [
    1,
    2,
    3
  ],
  "boolean": true,
  "null": null,
  "number": 123,
  "object": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
};

// Grab the array
var stuff = data.array;

// Check to see if the value is in the array
if(!(4 in stuff)){
 alert("Not in.");   
}
turnt
  • 3,235
  • 5
  • 23
  • 39
0

you could do some thing like this

if(typeof data.array[4] === "undefined"){
     // do your stuff
}
Sajjad Ashraf
  • 3,754
  • 1
  • 34
  • 35