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 语句,因为这看起来很乱。我可以进行某种类型的三元检查以查看该值是否未定义吗?
谢谢
解决方案
我将采用以下路径:创建一个类别数组,然后对其进行迭代以进行计数,因为您没有指定您的用例我不确定这是否适用于您。
但是你要做的事情是这样的:
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
}
}
推荐阅读
- php - PHP 选择不能在任何服务器上运行
- git - 将某些文件从主目录推送到 git repo 以更轻松地设置新盒子
- python - 在python中将多个整数变量重新编码为一个
- aggregate - ASP Clingo - 获取原子的确切数量
- javascript - messageParent 适用于桌面 Word 但不适用于 Web Word
- mysql - Mysql - 如何仅计算唯一访问次数
- r - 为什么 geom_rect 在各个方面看起来不同?
- node.js - Express rest api 在邮递员和开发中工作,但在部署时不工作
- php - Laravel 8 [Route: shop.show] [URI: {language}/shop/{shop}] 缺少必需的参数
- javascript - 更新数组反应钩子中数组的状态 onChange