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开发者_如何学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) {
}
精彩评论