Reputation: 5409
I have a two-dimensional array that is formatted as followed:
[["a",1], ["b",2]]
I want to change its formatting to this:
{"a":1,"b":2}
How can I do this? Sorry if it is an easy/stupid question.
Upvotes: 0
Views: 55
Reputation: 3763
Assuming the key won't appear twice:
var o = {};
[["a",1], ["b",2]].forEach(function(value) {o[value[0]] = value[1];});
Upvotes: 1
Reputation: 94429
You can iterate through the multidimensional array, assigning the inner arrays first index as the property and the second as the value.
var arr = [["a",1], ["b",2]];
var obj = {};
for(var i = 0; i < arr.length; i++){
obj[arr[i][0]] = arr[i][1];
}
Working Example http://jsfiddle.net/4Pmzx/
Upvotes: 2
Reputation: 74096
var result = {};
$.each([["a",1], ["b", 2]], function(){result[this[0]] = this[1]})
Upvotes: 2
Reputation: 46249
This is pretty easy:
var myList = {};
for( var i in myArray ) {
myList[myArray[i][0]] = myArray[i][1];
}
Upvotes: 2
Reputation: 1745
var arr = [["a",1], ["b",2]], obj = {}, i;
for (i = 0; i < arr.length; i++) {
obj[arr[i][0]] = arr[i][1];
}
Upvotes: 2
Reputation: 150010
I will assume you're sure that the same key won't appear twice (i.e., there won't be two inner arrays with "a"
):
var inputArray = [["a",1], ["b",2]],
outputObject = {},
i;
for (i = 0; i < inputArray.length; i++)
outputObject[inputArray[i][0]] = inputArray[i][1];
If that's not enough jQuery for you then I guess you can use $.each()
instead of a for
loop, etc., but in my opinion a plain for
loop is fine for this sort of thing.
Upvotes: 3