So I'm trying to use switch case for this but this doesn't seems to be the way.
I'm trying
switch (obj) {
case hasPropertyA:
console.log('hasPropertyA');
break;
case hasPropertyB:
console.log('hasPropertyB');
I was expecting that this does obj.hasPropertyX, and if it receive a true value show the console in any case statement, but not
Anyone have an way to do this? I have many properties do check so I can't just use an if( obj.hasOwnProperty(prop) ) {}, that's why I'm trying switch case statement
Well there is a way that you can use switch close to the way you are currently using it. You use a boolean statement as the switch like this:
var car = {
style: "volvo",
type: "sport"
}
function checkObjectProperties(obj) {
switch (true) {
case (obj.hasOwnProperty("style")):
console.log("has: property style")
break;
case (obj.hasOwnProperty("type")):
console.log("has property type");
}}
Keep in mind though that the switch-case will break at the first occurance of any true statement. In this case it will break at the first case and it will never enter the second one, even though it also equals as true.
Also always use a default case in the end to catch any objects that wont have any true cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With