John Cooper
John Cooper

Reputation: 7641

how to check in an array whether it has a key:value or not?

  var people =[{title:'Alan', hasChild:true},
        {title:'Alice', hasDetail:true},
        {title:'Amos', header'A'},
        {title:'Alonzo'},
        {title:'Brad'},
        {title:'Brent'},    
        {title:'Billy'},    
        {title:'Brenda'},   
        {title:'Callie'},
        {title:'Cassie'},   
        {title:'Chris'}];

I want to check in this array, whether it contains a key,value header:value in it or not. I want to check this for each elements.

Upvotes: 0

Views: 138

Answers (3)

Aron Rotteveel
Aron Rotteveel

Reputation: 83203

This should do it:

for (var i = 0, c = people.length;i < c;i++) {
    if (people[i].header) {
        // yay
        // not sure wether you want to check the value as well
        // but if that is the case, you'd do this
        if (people[i].header == 'A') {
            // do some more stuff
        }
    } else {
        // nay
    }
}

Upvotes: 1

naiquevin
naiquevin

Reputation: 7796

you can check if it is defined or not using typeof

for (var i in arr) {    
    if (typeof arr[i].header !== 'undefined') {
       //key present
    }  else {
       //key not present
    }  
}

Upvotes: 1

Thor Jacobsen
Thor Jacobsen

Reputation: 8851

for(var i = 0; i < array.length; ++i){
    if(array[i]["header"])
        //Do stuff with the header
    else
        //Do stuff without it
}

This should work... Though you've got an error in the element with the header - it should be header:'A', with the :

Upvotes: 1

Related Questions