Kinda late to the party but this should get the job done
2 ARRAYS
var ab = "",
a = [1, 2, 3, 4, 5, 6, 7, 8, 9],
b = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
x = b.length,
i = 0;
for (; i < x; i++) {
if (typeof a[i] == 'undefined' || typeof b[i] == 'undefined') continue;
ab += '[' + a[i] + ',"' + b[i] + '"],';
}
ab = JSON.parse("[" + ab.substr(0, --ab.length) + "]");
// ab[0][0] === 1
// ab[0][1] === 'a'
// ab[0] === [1, "a"]
// ab === [
// [1, "a"],
// [2, "b"],
// [3, "c"],
// [4, "d"],
// [5, "e"],
// [6, "f"],
// [7, "g"],
// [8, "h"],
// [9, "i"]
// ];
Try it at JSFIDDLE
assuming that a and b are the same length this will convert your arrays to json objects.
6 ARRAYS
You can expand your code to accommodate the more arrays like so
var ab = "",
a = [1, 2, 3, 4, 5, 6, 7, 8, 9],
b = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
c = ["h", "i", "j", "k", "l", "m", "n", "o", "p", "q"],
d = ["r", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
e = ["s", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
f = ["t", "b", "c", "d", "e", "f", "g", "h", "i", "j"],
x = b.length,
i = 0;
for (; i < x; i++) {
if (typeof a[i] == 'undefined' || typeof b[i] == 'undefined') continue;
ab += '[' + a[i] + ',"' + b[i] + '","' + c[i] + '","' + d[i] + '","' + e[i] + '","' + f[i] + '"],';
}
ab = JSON.parse("[" + ab.substr(0, --ab.length) + "]");
// ab[0] === [1, "a", "h", "r", "s", "t"]
// ab[0][5] === "t"
// ab[0][3] === "h"
6 ARRAY FIDDLE
EXPLANATION
We use one loop starting at 0
to the length of one of the array objects, this case b.length
.
Then for each iteration we convert the values of the array object to a multidimensional string appended to the object ab
. While ensuring that the values at each iteration aren't undefined
. after the loop we convert the multidimensional string to an JSON object with JSON.parse