Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to convert an Array to an Associative array [duplicate]

Possible Duplicate:
Convert flat array [k1,v1,k2,v2] to object {k1:v1,k2:v2} in JavaScript?

I want to convert an array to an associative array in JavaScript.

For example, given the following input,

  var a = ['a', 'b', 'c', 'd'];

I want to get the next associative array as output:

  {'a' : 'b', 'c' : 'd'}

How can I do that?

like image 623
Murtaza Khursheed Hussain Avatar asked Feb 27 '12 13:02

Murtaza Khursheed Hussain


3 Answers

Using .forEach:

var a = ['a', 'b', 'c', 'd'];
var obj_a = {};
a.forEach(function(val, i) {
    if (i % 2 === 1) return; // Skip all even elements (= odd indexes)
    obj_a[val] = a[i + 1];   // Assign the next element as a value of the object,
                             // using the current value as key
});
// Test output:
JSON.stringify(obj_a);       // {"a":"b","c":"d"}
like image 96
Rob W Avatar answered Oct 10 '22 08:10

Rob W


Try the following:

var obj = {};
for (var i = 0, length = a.length; i < length; i += 2) {
  obj[a[i]] = a[i+1];
}
like image 40
Rich O'Kelly Avatar answered Oct 10 '22 09:10

Rich O'Kelly


There is no such thing as an associative array, they're called Objects but do pretty much the same :-)

Here's how you would do the conversion

 var obj = {}; // "associative array" or Object
 var a = ['a', 'b', 'c', 'd'];
 for(index in a) {
     if (index % 2 == 0) {
         var key = a[index];
         var val = a[index+1];
         obj[key] = val;
     }
 }
like image 33
Willem Mulder Avatar answered Oct 10 '22 07:10

Willem Mulder