Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
tzortzik Avatar asked May 28 '14 09:05

tzortzik


People also ask

How to combine 2 arrays in jQuery?

The jQuery merge() method together merges the content of two arrays into the first array. This method returns the merged array. The merge() method forms an array containing the elements of both arrays. If we require the first array, we should copy it before calling the merge() method.

Can arrays have key value pairs?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg. We see above that we can loop a numerical array using the jQuery.

Can we subtract two arrays in javascript?

Using Underscore/Lodash LibraryThe Underscore and Lodash Library provides their implementation of the difference method _. difference, which returns values from an array that are not included in the other array. That's all about finding the difference between two arrays in JavaScript.


1 Answers

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));
like image 111
Korikulum Avatar answered Sep 22 '22 23:09

Korikulum