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
Murtaza Khursheed Hussain
15.3k7 gold badges61 silver badges83 bronze badges
3 Answers 3
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
Rob W
350k87 gold badges811 silver badges683 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
gintas
Nice, I didn't know about array.forEach(). Does it work across all browsers?
Felix Kling
@gintas: Only in those supporting ES5. But you can easily provide your own implementation.
Murtaza Khursheed Hussain
Ohh thats great. But y are you doing JSON.stringify(obj_a); ?
Murtaza Khursheed Hussain
@ROB W if you can give the exact implementation in pure javascript..
|
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
Rich O'Kelly
41.8k9 gold badges87 silver badges114 bronze badges
5 Comments
pimvdb
a.length would be sufficient since you're jumping in steps of 2 anyway.Rich O'Kelly
@pimvdb Doing so would be incorrect - consider an array of length 1...
Rob W
@rich.okelly Then it would be
{'a': undefined}, which is probably better than forgetting the key.Alexander Pavlov
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.pimvdb
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.
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
Willem Mulder
14.1k4 gold badges41 silver badges64 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js
{1: 'a', 2: 'b', 3: 'c', 4: 'd'}