3

I want to check using function by passing variable into parameter whether that property exists in the object or not.I tried all three mostly used ways to check the existing properties of an object,but still i'm getting the output as undefined.Can anyone tell me where i am wrong ?.

 var obj=[
        {
            "firstName": "James",
            "lastName": "Bond"

        }];

    function propExists(prop)
    {
      //I tried #1
      if(obj.hasOwnProperty(prop)===false)
       {
         return "Property doesn't exist";
       }
     //I tried #2
      if(!(prop in obj))
       {
         return "Property doesn't exist";
       }
     //I tried #3  
      if("undefined" === typeof(obj[prop]))
       {
         return "Property doesn't exist";
       }
    }

    console.log(propExists("Date of birth"));
cay cospete
  • 33
  • 1
  • 8

2 Answers2

1

You are actually using an array of objects.

So obj[0] will give you the first object.

Also hasOwnProperty is a boolean indicating whether or not the object has the specified property. So you dont need to specifically test it as true or false inside the if condition

 var obj = [{
   "firstName": "James",
   "lastName": "Bond"

 }];

 function propExists(prop) {
   if (obj[0].hasOwnProperty(prop)) {  // will be evaluated as true/false
     return "Propert exist";
   } else {
     return "Property doesn't exist";

   }

 }

 console.log(propExists("Date of birth"));

DEMO

brk
  • 48,835
  • 10
  • 56
  • 78
  • Yes,i know its an array and i did iterate through obj but i'm only stuck with this.How you can do that without else ?? – cay cospete Nov 26 '16 at 09:18
0

remove square brackets from obj that makes it array

var obj = {
  "firstName": "James",
  "lastName": "Bond"
};
Sreekanth
  • 3,110
  • 10
  • 22
Akshay
  • 815
  • 7
  • 16