0

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.

2
  • 3
    Wow, this question turned into "who can post this code the fastest"! Commented Mar 24, 2013 at 21:41
  • Hahaha I know. Free karma! Commented Mar 24, 2013 at 21:44

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2
var arr = [["a",1], ["b",2]], obj = {}, i;

for (i = 0; i < arr.length; i++) {
    obj[arr[i][0]] = arr[i][1];
}

Comments

2

This is pretty easy:

var myList = {};
for( var i in myArray ) {
    myList[myArray[i][0]] = myArray[i][1];
}

Comments

2
var result = {};
$.each([["a",1], ["b", 2]], function(){result[this[0]] = this[1]})

Comments

2

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/

Comments

1

Assuming the key won't appear twice:

var o = {};
[["a",1], ["b",2]].forEach(function(value) {o[value[0]] = value[1];});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.