2

I am retrieving JSON from a live streaming data. For the first call I am getting dataset array with time and value. But in the second JSON dataset array is empty. I want to check if dataset array contains time key.

Retrieved JSON after first call:

 {
  "activities-heart-intraday": {
    "dataset": [{
        "time": "00:00:00",
        "value": 91
    }, {
        "time": "00:01:00",
        "value": 92
    }, {
        "time": "00:02:00",
        "value": 92
    }],
    "datasetInterval": 1,
    "datasetType": "second"
  }
}

Retrieved JSON after second call:

{
  "activities-heart-intraday": {
    "dataset": [],
    "datasetInterval": 1,
    "datasetType": "second"
  }
}

I am doing

var value = JSON.parse(data);

if (value.hasOwnProperty('time')) {
   console.log("here");
} 

to check if time key exists in the JSON, but it's not working.

How can I check if a particular key exists in the array in json?

Akshay Talathi
  • 83
  • 1
  • 2
  • 13

4 Answers4

3

Firstly you have to check that dataset is not an empty array. Then check that time is defined.

This can be solved with:

if (dataset[0] !== undefined && dataset[0].time !== undefined)

or just:

if (dataset[0] && dataset[0].time)

If you want to iterate through the array:

dataset.forEach(function (data) {
   if (data.time) {
       // your code
   } 
});
GG.
  • 21,083
  • 14
  • 84
  • 130
  • alternatively, `dataset.length && dataset.every((obj) => obj.hasOwnProperty('time'))` – Hamms Apr 25 '16 at 22:52
  • my JSON response is in var data. When I try `if(data. activitiesHeartIntraday.dataset[0] !== undefined && data. activitiesHeartIntraday.dataset[0].time !== undefined` , it gives me error as: `TypeError: Cannot read property 'dataset' of undefined` – Akshay Talathi Apr 25 '16 at 23:12
  • [Because of the dashes in the key, you have to use the bracket notation](http://stackoverflow.com/a/4968448/652669): `data['activities-heart-intraday'].dataset`. – GG. Apr 25 '16 at 23:22
0

the data has a dataset array so we need to first check if the array is there and then if one of the arrays members has the time property

if( data.hasOwnProperty('dataset') && data.dataset.length != 0){    
  if( data.dataset[0].hasOwnProperty('time')){
    console.log('true');    
  }
}
0

Since in JS you can not natively set and access object properties those with a "-" character in it by dot notation you have define them as strings and use bracket notation instead to set and access them. So you can make a check like this

data["activities-heart-intraday"].dataset.length > 0 && data["activities-heart-intraday"].dataset.every(e => !!e.time);
Redu
  • 25,060
  • 6
  • 56
  • 76
  • it gives me error of `TypeError: Cannot read property 'dataset' of undefined`. I am checking if `data !== undefined` before checking dataset. Thanks – Akshay Talathi Apr 25 '16 at 23:23
  • @akshay talathi You should name the main object as `data` first or if it has a different name other than `data` then use that name in the place of `data` in the above conditional. – Redu Apr 25 '16 at 23:27
0

I can't really tell what data from your question is supposed to be but if it is the whole JSON object, then the most simple way is this:

if(data["activities-heart-intraday"]["dataset"][0]["time"])
  console.log('time is set)

But beware! If for example the dataset is not set, you'll get an error that you are trying to get time key from undefined and the code will crash. I'd recommend using simple recursive function like this:

function is_there_the_key(json, keys){
  if(keys.length == 0)
    return true           //we used the whole array, and every key was found
  let key = keys.shift()  //pop(get and remove) the first string from keys
  if(!json[key]){
    console.log(key + ' not found')
    return false          //one of the keys doesn't exist there
  }
  return is_there_the_key(json[key], keys)
}

Whether you return true or false, both of them will make their way up to the surface.

As the json parameter you pass the json you want to search in.

As the keys parameter you pass an array (mostly strings) of the keys in order they should go. For example:

if(is_there_the_key(data, ["activities-heart-intraday", "dataset", 0, "time"])
  //we found the key, do something here
Lee Shau
  • 11
  • 5