Some odds with hasOwnProperty

Hello,
I have a separate json file:

{
   "items":{
      "coll":
      {
         "coll1":
         {
         "id": 1,
         "name": "coll1",
         "example": ["example0", "example1"],
         "def": ["def0", "def1"]
         },

         "coll2":
         {
         "id": 2,
         "name": "coll2",
         "example": ["example0", "example1"],
         "def": ["def0", "def1"]
         }
      }
   }
}

and a javascript file:

var objects = new Array();
function getObjects(){
    $.getJSON("items.json", function(data){
        objects = data.items['coll']['coll1'].example[0];
        
        $.each(data, function(key, val){
            
            console.log(objects);
            if (data.items['coll']['coll1'].hasOwnProperty("id") == 1){
            	console.log("id=1");
            }else {
            	console.log("nothing happens");
            }
        })

    })
    };

Everything works fine, but when I change 1 onto 2:

 if (data.items['coll']['coll2'].hasOwnProperty("id") == 2)

it gives me nothing except the “else” part “nothing happens”.
It seems a bit odd to me. What am I doing wrong?

`hasOwnProperty is a function that returns true or false. In the if block you’re checking whether true or false equals 2. That is always false, therefore the log in the else condition is always executed.

I’ve just got it by myself. Thanks.

1 Like

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like