简体   繁体   中英

How to check in an object whether its has the key or not?

var object = [{key1:'value',key2:'value2'},{'key1:'value',key2:'value2}]

for (var key in object)
     {
      if(!object.hasOwnProperty(key)){continue;}

Why do we get error? Am i checking the right way.

I get an error cannot call hasOwnProperty in an Object - TypeError

object is not defined. Check this revision:

var myarr = [{key1:'value',key2:'value2'},{key1:'value',key2:'value2'}];
//renamed to myarr to avoid confusion - and removed typos from your code. 
//myarr is now an array of objects

//loop through myarr
for (var i=0;i<myarr.length;i=i+1){

 //check if the element myarr[i] is indeed an object
 if (myarr[i].constructor === Object) {

   //loop through the object myarr[i]
   for (var key in myarr[i])  {

      //notice the removal of !
      if(myarr[i].hasOwnProperty(key)){
         /* do things */
      }
   }
 }
}

Is your for-loop correct? Try this

for (var key in array)
{
  ...

You have not defined object in your for loop. Your array of objects above is named array .

for (var key in array) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM