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?
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With