0

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.

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.

6
  • post your code and error Commented Sep 3, 2020 at 11:04
  • can you show how you implemented it with the map function? Commented Sep 3, 2020 at 11:04
  • Added the code snipped @user969068 Commented Sep 3, 2020 at 11:07
  • You may use conditional chaining (theme.subThemes?.map(..) Commented Sep 3, 2020 at 11:08
  • @YevgenGorbunkov Throw Syntax error: Unexpected token Commented Sep 3, 2020 at 11:10

1 Answer 1

1

how is that sounds?

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

or for returning empty array (ES6 syntax)

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

or for returning undefined without having error (ES6 syntax)

myJson.languages?.map(x => { ... });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.