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

Javascript 检查未定义类型的JSON响应,javascript,json,Javascript,Json,不久前我问了一个类似的问题,但意识到我偏离了主题。我正在调用后端,后端读取一个JSON文件并返回响应 public function getData() { return json_decode(file_get_contents($file_path, true)); } 从后端返回的文件采用以下形式 [ [ //Some data ], [ //Some data ], [ { "Category": "basketball"

不久前我问了一个类似的问题,但意识到我偏离了主题。我正在调用后端,后端读取一个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语句,因为这看起来很混乱。我可以做一些类型的三元检查,看看值是否未定义吗


谢谢

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

const catOne = (2 in response.data && 0 in response.data[2]) ? response.data[2][0]['Count'] : None;

但是您可能也应该遍历response.data[2]而不是像这样硬编码类别…

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

const catOne = (2 in response.data && 0 in response.data[2]) ? response.data[2][0]['Count'] : None;

但您可能也应该遍历response.data[2]而不是像这样硬编码类别…

我将采用以下路径: 创建一个类别数组,然后迭代计数,因为您没有指定您的用例,我不确定这是否适用于您

但你要做的是这样的:

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
    }
}
const categories=[];
for(设i=0;i
我会选择以下路径: 创建一个类别数组,然后迭代计数,因为您没有指定您的用例,我不确定这是否适用于您

但你要做的是这样的:

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
    }
}
const categories=[];
for(设i=0;i
阵列的长度不应硬编码。只需使用for循环并每次检查数组长度

阵列的长度不应硬编码。只需使用for循环并每次检查数组长度