8

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?

Community
  • 1
  • 1
Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83

3 Answers3

16

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"}
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Nice, I didn't know about array.forEach(). Does it work across all browsers? – gintas Feb 27 '12 at 13:23
  • 1
    @gintas: Only in those supporting ES5. But you can easily provide your own implementation. – Felix Kling Feb 27 '12 at 13:24
  • Ohh thats great. But y are you doing JSON.stringify(obj_a); ? – Murtaza Khursheed Hussain Feb 27 '12 at 13:25
  • @gintas "All modern browsers but IE." [citation](http://stackoverflow.com/questions/156696/which-web-browsers-natively-support-array-foreach) – Rob W Feb 27 '12 at 13:26
  • @ROB W if you can give the exact implementation in pure javascript.. – Murtaza Khursheed Hussain Feb 27 '12 at 13:27
  • @MurtazaHussain In the source which I linked, a fallback is provided: See MDN: [`.forEach` #Compatibility](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach#Compatibility). I am using [`JSON.stringify`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify) as a quick method to check whether the object contains the desired name-key pairs. – Rob W Feb 27 '12 at 13:31
6

Try the following:

var obj = {};
for (var i = 0, length = a.length; i < length; i += 2) {
  obj[a[i]] = a[i+1];
}
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
  • 1
    `a.length` would be sufficient since you're jumping in steps of 2 anyway. – pimvdb Feb 27 '12 at 13:21
  • @pimvdb Doing so would be incorrect - consider an array of length 1... – Rich O'Kelly Feb 27 '12 at 13:23
  • @rich.okelly Then it would be `{'a': undefined}`, which is probably better than forgetting the key. – Rob W Feb 27 '12 at 13:24
  • I'd warn against presence checks like `if (obj["foo"])...` or even `if ("foo" in obj)...`, since these will also detect fields found on the `obj`'s prototype (try `if ("toString" in obj)...` as an example). To be on the safe side, use `obj.hasOwnProperty("foo")` - this guarantees that the prototype will not be checked. – Alexander Pavlov Feb 27 '12 at 13:26
  • But then again it doesn't really make sense to convert an array with an odd number of elements into such an object, because there aren't clear pairs in that case. – pimvdb Feb 27 '12 at 13:26
2

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;
     }
 }
Willem Mulder
  • 12,974
  • 3
  • 37
  • 62