JavaScript的 - 检查特定的关键是在现有的JSON [英] JavaScript - Check if a particular key is available in the JSON

查看:177
本文介绍了JavaScript的 - 检查特定的关键是在现有的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个流媒体直播的数据检索JSON。
对于第一个电话我得到随着时间的推移和价值数据数组。但第二JSON数据数组是空的。我要检查,如果数据集数组包含时间的关键。

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.

第一次通话后检索JSON:

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

第二个电话后,检索JSON:

Retrieved JSON after second call:

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

我做的

var value = JSON.parse(data);

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

要检查时间重点在JSON存在,但它不工作。

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

如何检查特定键JSON数组中的存在?

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

推荐答案

首先,你必须检查不是一个空数组。然后检查定义的的时间。

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

这可以解决:

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

或者只是:

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

如果你想通过数组迭代:

If you want to iterate through the array:

dataset.forEach(function (data) {
   if (data.time) {
       // your code
   } 
});

这篇关于JavaScript的 - 检查特定的关键是在现有的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆