检查JSON响应中的未定义类型

时间:2019-06-12 22:32:18

标签: javascript json

不久前,我问了一个类似的问题,但意识到我已经脱离话题了。我正在呼叫后端,该后端读取JSON文件并返回响应

public function getData()
{
    return json_decode(file_get_contents($file_path, true));
}

从后端返回的文件采用以下格式

[
  [
    //Some data
  ],
  [
    //Some data
  ],
  [
    {
      "Category": "basketball",
      "Count": 12
    },
    {
      "Category": "football",
      "Count": 34
    },
    {
      "Category": "baseball",
      "Count": 244
    },
    {
      "Category": "softball",
      "Count": 11
    }
  ]
]

所以它是数组和对象数组的混合体。上面的对象数组是我感兴趣的。在前端,我正在尝试处理这些数据。此刻,我做类似的事情

const catOne = response.data[2][0]['Count'];
const catTwo = response.data[2][1]['Count'];
const catThree = response.data[2][2]['Count'];
const catFour = response.data[2][3]['Count'];

但是我注意到的是,有时传回的文件没有4个类别。因此,我得到了错误

TypeError: Cannot read property 'Count' of undefined

我想知道解决这个问题的最佳方法是什么?我真的不希望加载if / else语句,因为这看起来很凌乱。我可以进行某种类型的三元检查以查看该值是否未定义吗?

谢谢

3 个答案:

答案 0 :(得分:1)

您可以在访问“ Count”属性之前检查数组是否存在:

git remote -v

但是您也应该遍历response.data [2],而不是像这样对类别进行硬编码...

答案 1 :(得分:1)

我将采用以下路径: 创建类别数组,然后遍历该数组进行计数,因为您没有指定用例,所以我不确定这是否适合您。

但是您要做的是遵循这些原则:

const categories = [];
for ( let i = 0; i < response.data[2].length; i++) {
    let response_data = response.data[2][i];
    if (response_data !== undefined) {
         categories.push(response_data); // You could also be pushing the count in here
    }
}

答案 2 :(得分:0)

不应对数组的长度进行硬编码。只需使用for循环并每次检查数组长度即可。