Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking properties in obj using javascript

Tags:

javascript

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

like image 676
Wagner Moreira Avatar asked Dec 04 '25 17:12

Wagner Moreira


1 Answers

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.

like image 158
Kodz Avatar answered Dec 12 '25 16:12

Kodz