Dave Dave - 9 days ago 6
Javascript Question

How can I get an object's property name without redundant 'name' key inside the object? And how to return 'name' of a user-provided undefined object?

Is there any way to get the property name of an object without having some sort
of redundant 'name' property inside the object itself? This will mainly be used
in cases where we a user tries to fetch an object that doesn't exist.

For example:

let myObject = {
favoriteListing: {
name: 'favoriteListing',
category: 'favorite',
action: 'add'
},
sendListing: {
name: 'sendListing',
category: 'send',
action: 'sms'
}
};

let displayObj = (object) => {
if (!object) {
console.warn(`Whoa, cowboy. ${object.name} does not exist!`);
return;
} else {
return object;
}
}


And expected vs actual output:

displayObj(myObject.favoriteListing);
/*
Output:
=> { name: 'favoriteListing', category: 'favorite', action: 'add' }
*/

displayObj(myObject.dammitBatman);
/*
Desired Output:
=> Whoa, cowboy. 'dammitBatman' does not exist!

Actual Output:
=> TypeError: Cannot read property 'name' of undefined
*/

Answer

You'll have to test whether the property exists before referring to it.

let displayObj = (object, property) => {
    if (!object[property]) {
        console.warn(`Whoa, cowboy. ${property} does not exist!`);
        return;    
    } else {
        return object;
    }
}


displayObj(myObject, "joe");

displayObj(myObject, "sendListing");