Search code examples
javascriptjqueryarraysassociationsmootools

Jquery associate two arrays (key, value) into one array


How can I associate two arrays that contains keys and values into one array with key->value pairs?

In Mootools there is associate function which does:

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
sounds.associate(animals);
// returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}

Is there any similar function in JQuery to obtain the same result from those two arrays?

If not, how can I do it?


Solution

  • JavaScript doesn't really have associative arrays, but you can use an object instead.

    Array.prototype.associate = function (keys) {
      var result = {};
    
      this.forEach(function (el, i) {
        result[keys[i]] = el;
      });
    
      return result;
    };
    
    var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
    var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
    console.dir(sounds.associate(animals));