-2

I am requesting an API sending to it words to be searched then retrieving the data from the API. Unfortunately the xml tree is not patterned, so I need to parse the xml file for each word with if statement. like so:

    if((JSON.stringify(result["entry_list"]["entry"][0]["sound"][0]["wav"][0])) !== undefined) {
        ...
        ...
       }

I need to check if there are those elements in the xml, otherwise I will have an error saying: "TypeError: Cannot read property '0' of undefined".

The problems is that with that if I am not having success, so I would like to know what is the right way to lead with that situation?

Thanks in advance!

enter image description here

enter image description here

1 Answers1

0

You can use object-get so that it will not throw error if the path is not there.

const objectGet = require('object-get')

const colour = objectGet(mammal, 'fur.appearance.colour')
const text = objectGet(el, 'children[2].children[1].children[1].textContent')

and just check like if (text) {}

Tuan Anh Tran
  • 6,807
  • 6
  • 37
  • 54