user1907849 user1907849 - 7 months ago 13
Javascript Question

Converting flat array into array of array

I have an array called initialarray

var initialarray = new Array();


I have a variable and an object which needs to be pushed under the expansion of variable.

var initvar = "a";



var employeeobjects


contains five employeeobjects with name and desc.

I am building in this way which is resulting in flattened array.

var empArray = [initvar];
empArray.push(employeeobjects);
initialarray.push(empArray);


which is resulting in

initarray: Array[1]
>0 : Array[2]
0:"a"
1:Array[1] //employeeobjects


I need employeeobjects to come under
"a"
on expansion of "a". Can anybody please tell what modifications I need to make?

Edit:
The code goes like this:

var employeeobjects = [{
"name" : "a",
"desc" : "desc1"
},{
"name" : "b",
"desc" : "desc2"
}]


var initialarray = new Array();
var initvar = "a";
var empArray = [initvar];
empArray.push(employeeobjects);
initialarray.push(empArray);


The result should be:

initarray: Array[1]
>0 : Array[2]
0:"a"
> 1:Array[1] //employeeobjects


"a" and employeeobjects should not be in same level. employeeobjects should come under "a"

Answer

I need employeeobjects to come under "a" on expansion of "a". Can anybody please tell what modifications I need to make?

Looks like you are looking for a to be an object rather than a simple literal text.

Try something like this

var initvar = "a";
var employees = {};
employees[initvar] = employeeobjects;
initialarray.push(employees);
Comments