简体   繁体   中英

Checking properties in obj using 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

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.

You're using switch() wrong. You must have a variable or expressions to check as the parameter. An object will not work.

For example, you can do:

var string = "hello";
switch(string) {
    case "green":
        // do something
        break;
    case "hello":
        // do something
        break;

     // and so on...
}

If you had a list of properties, and if you stored them in an array, you can iterate over the array and check if each one is defined:

var properties = ["propertyA", "propertyB", "etc."];
for(var i = 0; i < properties.length; i++) {
    if(obj[properties[i]] != undefined) {
        console.log("Has property: " + properties[i]);
    }
}

You can see a working example on JSFiddle.net.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM