Skip to content
Advertisement

The “TypeError: Cannot convert undefined or null to object” when using filter method” in Vue.js application

The code looks as following:

getSections () {
  if (!this.document) {
    return []
  }

  return Object.keys(this.document.Sections).filter(x => this.document.Sections[x])
}

The this.document.Sections is object that contains properties (objects as well).

How to get rid of this error?

Advertisement

Answer

As the message says, this error comes from passing null to Object.keys. Try it in the console:

Object.keys(null)

VM198:1 Uncaught TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)

So, in your code this.document.Sections is null.

Here you have an option to fix it. Hope it helps.

function getSections() {
    return (this.document && this.document.Sections)
        ? Object.keys(this.document.Sections)
            .filter(x => this.document.Sections[x])
        : [];
}

See it in a snippet:

var test = {
    document: {
        Sections: {
            a: 1,
            b: undefined,
            c: 3
        }
    }
};

function getSections() {
    return (test.document && test.document.Sections)
        ? Object.keys(test.document.Sections)
            .filter(x => test.document.Sections[x])
        : [];
}
console.log(getSections())
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement