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?
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?
Share Improve this question edited Jun 20, 2019 at 13:44 demo 6,24519 gold badges83 silver badges158 bronze badges asked Jun 20, 2019 at 13:07 tesicgtesicg 4,06316 gold badges68 silver badges127 bronze badges 4- 2 can you please confirm if this.document.Sections is a non-empty object, try consoling it. – akshay kishore Commented Jun 20, 2019 at 13:10
- I've updated the original post. Please, take a look above. – tesicg Commented Jun 20, 2019 at 13:12
-
The code does in no way guarantee, that
this.document.Sections
is notundefined
(ornull
, though unlikely), even after the update. – ASDFGerte Commented Jun 20, 2019 at 13:14 - 1 Does this answer your question? How to resolve TypeError: Cannot convert undefined or null to object – Donald Duck is with Ukraine Commented Aug 26, 2020 at 10:57
4 Answers
Reset to default 4As the message says, this error es 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())
You need to check if this.document.Sections
is null or undefined
getSections () {
if (!this.document && !this.document.Sections) {
return []
}
return Object.keys(this.document.Sections).filter(x => this.document.Sections[x])
}
[1,null,2,undefined,{},3].filter(x => isFinite(x) && x > 1)
produces [2, 3]
[1,null,2,undefined,{},3].filter(x => x !== null && x != undefined)
produces[1, 2, {}, 3]
Just specify the correct criteria in the filter.
That error could be more helpfully written as: "one of your variables was null or undefined"
There aren't many to choose from, but you will need to do a little local debugging to work out which, and why.