JavaScript arrays does not work like those in for instance PHP which can work as associative arrays. However, due to JavaScript's dynamic nature, and the fact that an Array is a subclass of Object, you can still attach arbitrary properties on to a Array. The length
property will however not reflect this (as you have discovered).
If you're using newer browsers/polyfills (like core-js
), I recommend going with Map
instead (Documentation). Otherwise, use a simple object ({}
), and use Object.keys
on the object to get the keys.
Example of the later:
var mappings = {};
mappings['foo'] = 'bar';
Object.keys(mappings); // returns ['foo']
mappings[Object.keys(mappings)[0]]; // returns 'bar'
// Loop through all key-value pairs
Object.keys(mappings).forEach(function(key) {
var value = mappings[key];
// Do stuff with key and value.
});