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

7

7

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?

Reminisce answered 28/5, 2014 at 9:51 Comment(1)
MooTools has much more non-DOM methods than jQuery. You could use MooTools instead of jQuery... then you have all DOM methods from MooTools, plus the extra sugar like this .associate() method.Doily
C
6

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));
Cardboard answered 28/5, 2014 at 9:59 Comment(1)
if i have a duplicate values in animals array and i want to append this value with previous (let say in Array) value, it returns a number instead of value. var animals = ['Cow', 'Pig', 'Dog', 'Cow']; var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];Locule
S
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
    }, {})
} 
Stoicism answered 31/5, 2014 at 20:43 Comment(0)
C
1

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"
Cranwell answered 28/5, 2014 at 9:57 Comment(0)
O
1

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


Overcome answered 28/5, 2014 at 9:59 Comment(0)
S
0

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));
Sheena answered 28/5, 2014 at 10:11 Comment(0)
N
0

If you can add a dependency like lodash to your project, then it's as easy as:

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

This will produce a new array of arrays:

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

To the result, apply the lodash function fromPairs:

let finalResult = _.fromPairs(resultArrayFromPreviousCode)

finalResult is now:

{ key1: value1, key2: value2 }

Hope that helps!

Nettle answered 22/3, 2017 at 5:49 Comment(0)
Y
0

for...of Method

You can also use a for...of statement in conjunction with Array.prototype.entries() to create an object using one array for keys and another for values:

const array_combine = (keys, values) => {
  const result = {};
  
  for (const [index, key] of keys.entries()) {
    result[key] = values[index];
  }
  
  return result;
};

const animals = ['Cow', 'Pig', 'Dog', 'Cat'];
const sounds  = ['Moo', 'Oink', 'Woof', 'Miao'];

console.log(array_combine(animals, sounds));
Yesterday answered 2/11, 2018 at 3:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.