JQuery binds two arrays (key, value) into one array

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

Mootools has a function associatethat 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 get the same result from these two arrays?

If not, how can I do this?

+4
source share
6 answers

JavaScript doesn't actually 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));
+4
source

jQuery, , JS ( 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);

:

Cat: "Miao"
Cow: "Moo"
Dog: "Woof"
Pig: "Oink"
+1

, :

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;
};

, , :

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
var x = sounds.associate(animals);

x {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}


DEMO - Mootool


+1

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));
+1

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} 

IE 9, Polyfill mdn , , .. < 9.

, :

function associate(keys, values){
    return keys.reduce(function (previous, key, index) {
        previous[key] = values[index];
        return previous
    }, {})
} 
+1

, , lodash , :

let result = _.zip([key1, key2], [value1, value2])

This will create a new array of arrays:

[[key1, value1], [key2, value2]]

As a result, apply the lodash fromPairs function:

let finalResult = _.fromPairs(resultArrayFromPreviousCode)

finalResult now:

{ key1: value1, key2: value2 }

Hope this helps!

0
source

Source: https://habr.com/ru/post/1542299/


All Articles