Testing Objects for Properties (solution please)

Testing Objects for Properties (solution please)
0

#1

Tell us what’s happening:

Your code so far


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

function checkObj(checkProp) {
  // Your Code Here
  
  return "Change Me!";
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/testing-objects-for-properties/


#2

I don’t want to provide the solution, it’s easy to do this if you have completed all previous challenges.

Hint*
FCC clearly says that using hasOwnProperty to check if a prop is available or not in an Object.

How to check this? Loops and Conditionals.

Here we need to check for only one property so use conditions to solve the challenge.


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

function checkObj(checkProp) {
  // Your Code Here
  if(myObj.hasOwnProperty("gift")){
return "pony";
  }
  else if(myObj.hasOwnProperty("pet")){
    return "kitten";
  }
  else if(myObj.hasOwnProperty("house"){
    return "Not Found";
  }
  
}

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

#4

The way you have written will work just fine but what if you don’t know the value of a dynamically populated JSON Object?
In dynamic situations, your code will not work.

You have to write the code so that it checks for given property and return it’s value.

function checkObj(checkProp) {
  // Your Code Here
  if(myObj.hasOwnProperty(checkProp)){
    return myObj[checkProp]
  } else {
     return "Not Found";
  }
  
}