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.
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.
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.
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/