简体   繁体   中英

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"

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM