How to check whether my key exists in array of object

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'
    });
}

To make it easier you should store your data thusly:

var map = {
       "key1": "z",
       "key2": "u"
};

Then you can do your check and if your keys don't conflict with any existing properties on the object and you don't need null values you can make it easier.

if (!map["key1"]) {
   map["key1"] = "z";
}

If you really need the full object (yours is after all just an example), I would store the object as the value of the key, not just store the objects in the array. That is, make it a map, not an array.

Tags:

Javascript