Delmon Young
Delmon Young

Reputation: 2053

jQuery see if key existing in entire JSON

I've got some JSON data in which I'm trying to check if a key is contained in the entire array and add a class or do something else. If there is one key contained in the array I want to perform an action otherwise if there is no key do something. I've been banging my head for hours ,inArray doesn't seem to be working for me or hasOwnProperty. I've got to be doing something stupid simple wrong here. Kind of a newb so please include code samples were applicable.

JS Fiddle: http://jsfiddle.net/AtC4G/

var data={"users":[
    {
        "firstName":"Ray",
        "lastName":"Villalobos",
        "userName":"rvilla",
        "joined": {
            "month":"January",
            "day":12,
            "year":2012
        }
    },
    {
        "firstName":"John",
        "lastName":"Jones",
        "joined": {
            "month":"April",
            "day":28,
            "year":2010
        }
    },
    {
        "firstName":"John",
        "lastName":"Johnson",
        "userName": "jjoe"
    }
]}

if($.inArray('userName', data.users) == -1) { alert('not in array'); }

if(data.users.hasOwnProperty('userName')){
alert('do something');
}

Upvotes: 0

Views: 70

Answers (3)

Thomas Junk
Thomas Junk

Reputation: 5676

To find out, whether a property is set, I would go for a native JS.solution:

 function containsKey(key){ return function(el){
     return el[key]!==undefined;
 }};

 containsUserName=containsKey("userName");

 console.log(data.users.some(containsUserName))

This is all you need. containsKey is a closure, which saves the key, for which you are looking for.

containsUsername is the function, which is used to look for a specific property.

Read the MDN documentation of Array.some() for compatibility etc.

Here is a Fiddle to play with.

If you want to extract that element: Array.filter() might be of interest.

Upvotes: 0

Uvadzucumi
Uvadzucumi

Reputation: 11

you can compare a variable with a undefined value

for(user_index in data.users){
    user=data['users'][user_index];
    if(user.userName==undefined){
        alert('username undefined in user '+user.firstName+' '+user.lastName);
    }
}

Upvotes: 0

elixenide
elixenide

Reputation: 44851

The [ indicates an array, so you need to treat it as an array (data.users[0], not just data.users):

if($.inArray('userName', data.users[0]) == -1) { alert('not in array'); }

if(data.users[0].hasOwnProperty('userName')){
    alert('do something');
}

Upvotes: 2

Related Questions