John Cooper John Cooper - 3 years ago 209
Javascript Question

How to check whether my key exists in array object

var arr = [{
key: "key1", value: "z"
}, {
key: "key2", value: "u"
}, {
...
}];


How to check whether my
key:"key1"
exists already or not. If it does not exist, i need to add the key in ma array.

if(arr.hasOwnProperty("key1")){
arr.unshift({key:"key1", value:"z"});
}

Answer Source

Since you've got an Array filled with Objects, you need to do it like:

(ES3)

function lookup( name ) {
    for(var i = 0, len = arr.length; i < len; i++) {
        if( arr[ i ].key === name )
            return true;
    }
    return false;
}

if( !lookup( 'key1' ) ) {
    arr.push({
        key: 'key1',
        value: 'z'
    });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download