[英]Skip Undefined Error if an object key is missing in Javascript
I would like to know as to how can we skip Undefined error being throw if a key is missing.我想知道如果缺少键,我们如何跳过抛出的未定义错误。
[
{
"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"
]
}
]
Let say I have an array object like this above, If I do a map over it, it is giving me an error because I don't have a subThemes key in the 3rd object.假设我有一个像上面这样的数组对象,如果我对它进行映射,它会给我一个错误,因为我在第三个对象中没有 subThemes 键。
const children = theme.subThemes
.map(subTheme => {
const { subThemes = [] } = aggregations;
...rest of the code}
TypeError: Cannot read property 'map' of undefined
How do I bypass the undefined error?如何绕过未定义的错误? Thanks in advance.
提前致谢。
how is that sounds?听起来怎么样?
if ( Array.isArray(myJson.languages))
myJson.languages.map(.....
or for returning empty array (ES6 syntax)或返回空数组(ES6 语法)
(myJson.languages || []).map(x => { .... });
or for returning undefined without having error (ES6 syntax)或返回 undefined 没有错误(ES6 语法)
myJson.languages?.map(x => { ... });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.