首页 > 解决方案 > 如果 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

如何绕过未定义的错误?提前致谢。

标签: javascriptjsonreactjs

解决方案


听起来怎么样?

if ( Array.isArray(myJson.languages))
     myJson.languages.map(.....

或返回空数组(ES6 语法)

(myJson.languages || []).map(x => { .... });

或返回 undefined 而没有错误(ES6 语法)

myJson.languages?.map(x => { ... });

推荐阅读