Testing Objects for Properties miguel

Testing Objects for Properties miguel
0.0 0

#1

Tell us what’s happening:

Hi, I do not understand how to solve this problem.
Can you give me a clue?
checkObj(“gift”) should return “pony”.
checkObj(“pet”) should return “kitten”.
checkObj(“house”) should return “Not Found”.

Your code so far


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

function checkObj(checkProp) {
  // Your Code Here
  myObj.hasOwnProperty()
  return checkProp;
}

// Test your code by modifying these values
checkObj("gift");

#2

Haiiiyo! The instruction of the challenges has two parts:

Modify the function checkObj to test myObj for checkProp.

You haven’t actually tested your object for to see whether or not a property exist because you are not actually providing a parameter to the hasOwnProperty() method. That is:

myObj.hasOwnProperty(); // false, and will always be false
myObj.hasOwnProperty('gift'); // true, because myObj has a property called gift

Another example that may help:

var obj = { text: "nyanpasu" };
var prop = 'text';

obj.hasOwnProperty(prop); // true

If the property is found, return that property’s value. If not, return “Not Found”.

The instruction doesn’t ask you to return the variable checkProp at all. In addition to the problem with the first part of the instruction, you should be using the value returned by the hasOwnProperty() method to determine what to return. Your code, at the moment, is the same as a function that simply returns the argument:

function checkObj(checkProp) {
  return checkProp;
}

Without spoiling it for you, the instructions actually want you to do this:

function checkObj(checkProp) {
  // 1. Use the hasOwnProperty() method to check if checkProp exists in checkObj
  // 2. If checkProp exists in checkObj, return the property's **value**, that is, if checkProp
  //    is "gift", you should return "pony"
  // 3. Otherwise, if checkProp doesn't exist in checkObj, return the string "Not Found"
}

I hope that helps!


#3

It only occurs to me, but it does not work:

function checkObj(checkProp) {
   if (myObj.hasOwnProperty(checkProp)) {
       return myObj(checkProp)
 }
return "Not Found"
}
checkObj("gift")

#4

Close! It’s just a syntax issue with myObj(checkProp)—which actually means calling the myObj function with checkProp as an argument.

To get the value of a property in an object using a variable you should use square brackets [] instead, this syntax is also called “key access”:

myObj[checkProp];

Example:

const obj = { str: 'nyanpasu' };
const prop = 'str';

console.log(obj[prop]); // "nyanpasu"

I hope that helps! :smile:


#5
 return myObj[checkProp]