Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

var associativeArray = [];  associativeArray['key1'] = 'value1'; associativeArray['key2'] = 'value2'; associativeArray['key3'] = 'value3'; associativeArray['key4'] = 'value4'; associativeArray['key5'] = 'value5';  var key = null; for(key in associativeArray) {     console.log("associativeArray[" + key + "]: " +  associativeArray[key]);         }  key = 'key3';  var obj = associativeArray[key];          // gives index = -1 in both cases why? var index = associativeArray.indexOf(obj);  // var index = associativeArray.indexOf(key);    console.log("obj: " + obj + ", index: " + index);    

The above program prints index: -1, why? Is there any better way to get index of an object in an associative array without using loops?

What if I want to delete 'key3' from this array? the splice function takes first parameter as index which must be an integer.

like image 911
gmuhammad Avatar asked Feb 14 '12 07:02

gmuhammad


People also ask

How do you find the index of an object in an array of objects?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.

How do you find the index of an object property?

To get a value of an object by index, call the Object. values() method to get an array of the object's values and use bracket notation to access the value at the specific index, e.g. Object. values(obj)[1] . Copied!

Can you index a JavaScript array?

JavaScript arrays are zero-indexed: the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .


1 Answers

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.

like image 135
georg Avatar answered Sep 24 '22 10:09

georg