javascript - 如果 Javascript 中缺少对象键,则跳过未定义错误
问题描述
我想知道如果缺少键,我们如何跳过抛出未定义的错误。
[
{
"id": "foo1",
"name": "Test1",
"description": "random test1",
"languages": [
"en"
],
"subThemes": [
{
"id": "1",
"name": "Bike"
},
{
"id": "2",
"name": "Testy",
"description": "Testing this thing1"
}
]
},
{
"id": "foo2",
"name": "Test",
"description": "random test2",
"languages": [
"en"
],
"subThemes": [
{
"id": "3",
"name": "Bike2"
},
{
"id": "4",
"name": "Testy2",
"description": "Testing this thing2"
}
]
},
{
"id": "foo3",
"name": "Test3",
"description": "random test3",
"languages": [
"en"
]
}
]
假设我有一个像上面这样的数组对象,如果我在它上面做一个映射,它会给我一个错误,因为我在第三个对象中没有 subThemes 键。
const children = theme.subThemes
.map(subTheme => {
const { subThemes = [] } = aggregations;
...rest of the code}
TypeError: Cannot read property 'map' of undefined
如何绕过未定义的错误?提前致谢。
解决方案
听起来怎么样?
if ( Array.isArray(myJson.languages))
myJson.languages.map(.....
或返回空数组(ES6 语法)
(myJson.languages || []).map(x => { .... });
或返回 undefined 而没有错误(ES6 语法)
myJson.languages?.map(x => { ... });
推荐阅读
- javascript - 如何在 JavaScript 函数中使用 switch
- c# - 如何在c#中检查串口是否断开连接
- nginx - 根据 NGINX 中的标头请求加载站点
- python - 为什么我得到一个 TypeError: PySide2.QtCore.QStringListModel.setData(): no enough arguments
- javascript - 为什么外部 javascript 文件在 Rails 6 中不起作用?
- rsync - rsync:如何在一次调用中复制多个子目录
- unit-testing - kotlin如何在测试中覆盖const
- c++ - 未解析的外部符号 _ippiResize_8u_*
- java - 获取 Map 中最内部的值作为`Map 中的列表
>>>` Java - laravel - 使用 Laravel 从 AWS SQS 提取数据并更新到 ElasticSearch