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?
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"}
Try the following:
var obj = {};
for (var i = 0, length = a.length; i < length; i += 2) {
obj[a[i]] = a[i+1];
}
There is no such thing as an associative array, they're called Object
s 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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With