I think what you need is a safe-read method for a property on an object
. You can create a method that receives an object
and a key
and safe read that property chaining the verifications. Examples of chaining you can use to approach this are:
obj && obj.key ? obj.key : "N/A"
or
(obj || {}).key || "N/A"
or
obj && obj.key || "N/A"
And in some future (I hope not so long) maybe you can use next one:
obj?.key || "N/A"
Reference
Finally, a minimal example of a generic safe-read method could be:
let obj1 = null;
let obj2 = {};
let obj3 = {name: ""}
let obj4 = {name: "John"}
const safeReadObj = (obj, key) => obj && obj[key] || "N/A";
// Test cases:
console.log(safeReadObj(obj1, "name"));
console.log(safeReadObj(obj2, "name"));
console.log(safeReadObj(obj3, "name"));
console.log(safeReadObj(obj4, "name"));