开发者

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

开发者 https://www.devze.com 2023-03-21 15:11 出处:网络
var object = [{key1:\'value\',key2:\'value2\'},{\'key1:\'value\',key2:\'value2}] for (var key in object)
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开发者_如何学Go 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) {

}
0

精彩评论

暂无评论...
验证码 换一张
取 消