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?

asked Feb 27, 2012 at 13:15
8
  • 3
    You mean to an Object? Do you want the array members to be the keys or values? Commented Feb 27, 2012 at 13:16
  • Well... It's an associative array, but uses number like key. It's similar to: {1: 'a', 2: 'b', 3: 'c', 4: 'd'} Commented Feb 27, 2012 at 13:17
  • 1
    @DavidRodrigues But 0 based, not 1 based! Commented Feb 27, 2012 at 13:18
  • 1
    Actually I want above array to be converted into var a = ['a':'b', 'c':'d']; Commented Feb 27, 2012 at 13:18
  • 1
    Edit your question with those details! Commented Feb 27, 2012 at 13:19

3 Answers 3

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"}
answered Feb 27, 2012 at 13:19
Sign up to request clarification or add additional context in comments.

6 Comments

Nice, I didn't know about array.forEach(). Does it work across all browsers?
@gintas: Only in those supporting ES5. But you can easily provide your own implementation.
Ohh thats great. But y are you doing JSON.stringify(obj_a); ?
@gintas "All modern browsers but IE." citation
@ROB W if you can give the exact implementation in pure javascript..
|
6

Try the following:

var obj = {};
for (var i = 0, length = a.length; i < length; i += 2) {
 obj[a[i]] = a[i+1];
}
answered Feb 27, 2012 at 13:19

5 Comments

a.length would be sufficient since you're jumping in steps of 2 anyway.
@pimvdb Doing so would be incorrect - consider an array of length 1...
@rich.okelly Then it would be {'a': undefined}, which is probably better than forgetting the key.
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.
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.
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;
 }
 }
answered Feb 27, 2012 at 13:19

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.