3

I'm trying to check if myObj has or not "x" properties. However, is not returning anything when myObj doesn't have the property I'm looking for. Here is the code:

var myObj = {
    gift: "pony",
    pet: "kitten",
    bed: "sleigh"
};

function checkObj(checkProp) {

    if(myObj.hasOwnProperty("gift")){
        return myObj[checkProp];
    } else if(myObj.hasOwnProperty("pet")){
        return myObj[checkProp];
    } else if(myObj.hasOwnProperty("bed")){
        return myObj[checkprop];
    } else {
        return "Not Found";
    }
}

4 Answers 4

3

Note: if (myObj.hasOwnProperty("gift")) will always enter because myObj has the property gift so other conditions will never be evaluated.

Don't you wanted to do just this?

var myObj = {
    gift: "pony",
    pet: "kitten",
    bed: "sleigh"
};

function checkObj(checkProp) {

    if (myObj.hasOwnProperty(checkProp)) {
        return myObj[checkProp];
    }
    else {
        return "Not Found";
    }
}

console.log(checkObj("gift"));
console.log(checkObj("foo"));

Sign up to request clarification or add additional context in comments.

Comments

1

You should check the property you are passing instead of hardcoding the property in the if clauses.This could then be reduced to a ternary operator. Because if you have a variable which stores the property, use the [] notation which uses the value of the property to lookup inside your object.

If checkProp variable is 'gift' then myObj[checkProp] becomes myObj.gift as the value of the the checkProp variable is used.

function checkObj(checkProp) {
   return myObj[checkProp]?myObj[checkProp]:"Not found"
}

Comments

1

You can use Object.keys to get the list of own properties, then invoke Array.includes to look for the specific property and return it's value.

const myObj = {
    gift: "pony",
    pet: "kitten",
    bed: "sleigh"
};
function checkObj(myObj, key){
  return Object.keys(myObj).includes(key) ? myObj[key] : "Not found";
}
console.log(checkObj(myObj, 'gift'));
console.log(checkObj(myObj, 'pet'));
console.log(checkObj(myObj, 'foo'));

Comments

1

You can do this using the in operator to test if the specified property is in the object:

const myObj = {
    gift: "pony",
    pet: "kitten",
    bed: "sleigh"
};

function getProp(obj, prop) {
  return prop in obj ? obj[prop] : undefined;
}

console.log(getProp(myObj, 'gift'));
console.log(getProp(myObj, 'pet'));
console.log(getProp(myObj, 'bed'));
console.log(getProp(myObj, 'noProp'));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.