edraven
edraven

Reputation: 25

convert array in array of arrays in Javascript

I would like to convert an array like this :

url : Array

0:"michael"
1:"jason"

url : Array

0:Array
 0:"michael"
1:Array
 0:"jason"

I need it for add data to (jquery) datatable ("aaData": exceptions,)

Upvotes: 0

Views: 3557

Answers (1)

Boris Šuška
Boris Šuška

Reputation: 1794

In JavaScript the Array is this: ["michael", "jason"]

This is an Object: {0: "michael", 1: "jason"}

To convert Array as you wrote you can use script like this:

var a = ["michael", "jason"];
for (var i=0; i<a.length; i++) {
    a[i] = [a[i]];
}

To convert Object as you wrote you can use script like this:

var obj = {0: "michael", 1: "jason"};
for (var i in obj) { // here is a difference - using `in` keyword
    obj[i] = [obj[i]];
}

Here is a working fiddle.

UPDATE:

For modern browsers (IE9+, FF1.5+) you can use map method of Array object:

var a = ["michael", "jason"];
a = a.map(function(item) {
    return [item];
});

Upvotes: 1

Related Questions