Jquery associate two arrays (key, value) into one array
Solution 1
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));
Solution 2
You can use Array.prototype.reduce
var keys = ['a', 'b', 'c'],
values = [1, 2, 3],
associated = keys.reduce(function (previous, key, index) {
previous[key] = values[index];
return previous
}, {})
console.log(associated) // Object {a: 1, b: 2, c: 3}
reduce is not supported natively on IE<9 but you can safely use the Polyfill on the mdn site which you can include using a conditional comment to target ie <9 only.
If you want a reusable function is pretty straightforward to do:
function associate(keys, values){
return keys.reduce(function (previous, key, index) {
previous[key] = values[index];
return previous
}, {})
}
Solution 3
Not jQuery, but simple enough to be achieved with pure JS (here's a fiddle):
var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var assoc = [];
for(var i=0; i<animals.length; i++) {
assoc[animals[i]] = sounds[i];
}
console.log(assoc);
prints:
Cat: "Miao"
Cow: "Moo"
Dog: "Woof"
Pig: "Oink"
Solution 4
You could write your own similar to this:
Array.prototype.associate = function(arr){
var index,
output = Object.create(null);
for(index = 0; index < this.length; index++){
output[arr[index]] = this[index];
}
return output;
};
Then you can use it as expected, similar to this:
var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var x = sounds.associate(animals);
The result in x
is {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}
DEMO - Replicating Mootool's associate function
Solution 5
you can use in java scipt.
Array.prototype.associate= function(){
var that = this;
var associated ={};
var len = that.length;
for(var i=0; i < len; i++){
associated[that[i]] = value[i];
}
return associated;
}
var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
console.log(animals.associate(sounds));
tzortzik
Updated on June 16, 2022Comments
-
tzortzik almost 2 years
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?