javascript: how to get index of an object in an associative array?

indexOf only works with pure Javascript arrays, i.e. those with integer indexes. Your “array” is actually an object and should be declared as such

var associativeArray = {}

There’s no built-in indexOf for objects, but it’s easy to write.

var associativeArray = {}

associativeArray['key1'] = 'value1';
associativeArray['key2'] = 'value2';
associativeArray['key3'] = 'value3';
associativeArray['key4'] = 'value4';
associativeArray['key5'] = 'value5';

var value="value3";
for(var key in associativeArray)
{
    if(associativeArray[key]==value)
         console.log(key);
}

Without loops (assuming a modern browser):

foundKeys = Object.keys(associativeArray).filter(function(key) {
    return associativeArray[key] == value;
})

returns an array of keys that contain the given value.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)