Code:
if (content.context_data.custom_topic === undefined) {
console.log('doesnt work');
}
and
if (typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined') {
console.log("Inside if")
}
Error:
source_code.js:71 Uncaught TypeError: Cannot read property 'custom_topic' of null
I want to check on content.contect_data.custom_topic if it is available or not. I've been searching Stackoverflow a lot, but every variation I found seems not working.
I wish to create something like:
if(content.context_data.custom_topic !== undefined)
{
var custom_topic = content.context_data.custom_topic;
}
Note: I have to use native JS.
3 Answers 3
You can check it as:
if (content.context_data && content.context_data.custom_topic === undefined) {
console.log('doesnt work');
}
Comments
If you want to check a property of an object, you have to check it's parent as well, because if the parent is undefined then your code will throw an error.
if (
content !== undefined ||
content.context_data !== undefined ||
content.context_data.custom_topic !== undefined
) {
console.log("doesn't work");
} else {
var custom_topic = content.context_data.custom_topic;
}
Or you can leave the undefined and chain it like this
if (
content &&
content.context_data &&
content.context_data.custom_topic
) {
// do stuff
}
Or you can create an algorithm that expects an object and a property name, eg. custom_topic and returns a boolean wheter it exists or not.
const propExists = (obj: any, propName: string): boolean => {
const propNames = Object.getOwnPropertyNames(obj);
let exists = false;
if (propNames.includes(propName)) {
exists = true;
} else {
for (let i = 0; i < propNames.length; i++) {
const prop = propNames[i];
if (
typeof obj[prop] === "object" &&
Object.getOwnPropertyNames(obj[prop]).length > 0
) {
exists = propExists(obj[prop], propName);
}
}
}
return exists;
};
const myObj = {
content: {
context_data: {
custom_topic: "My topic",
},
},
};
console.log(propExists(myObj, "custom_topic"));
But obviously, you don't need an algorithm if you wouldn't use it more than once.
Comments
Because context_data can be null you can use optional chaining
var content = {};
if (content.context_data?.custom_topic !== undefined) {
console.log(content.context_data.custom_topic);
} else {
console.log("undefined value");
}
content.context_data = { custom_topic: "test"};
if (content.context_data?.custom_topic !== undefined) {
console.log(content.context_data.custom_topic);
} else {
console.log("undefined value");
}
if(content.context_data !== null && content.context_data.custom_topic !== undefined)? 😊?.)