Search code examples
arraystypescriptjavascript-objects

Populate an array of array of objects


I must populate an array of array of objects to get something like this:

let dataObj = [
    [
        { content: "test1"}, 
        { content: "test2"},
        { content: "test3"}
    ], 
    [
        { content: "test4"},
        { content: "test5"},
        { content: "test6"}
    ]
]

I start from an array of arrays like this:

data = [["test1", "test2", "test3"], ["test4", "test5", "test6"]]

I tried with:

let dataObj = <any>[[{ }]];

for (let i = 0; i < data.length; i++) {
  for (let j=0; j < data[i].length; j++) {
    dataObj[i][j].content = data[i][j];
  }
}

but after populating the first ([0][0]) it stops and the error is an

uncaught in promise...

(I work in Angular-TypeScript)

I tried also with:

dataObj.push(i,j,{content: data[i][j]});

It gets a result but it's completely wrong.


Solution

    1. Add an array into the root array.

    2. Add an object into the nested array.

    let dataObj: { content: any;[key: string]: any }[][] = [];
    
    for (let i = 0; i < data.length; i++) {
       dataObj.push([]);
    
       for (let j = 0; j < data[i].length; j++) {
          dataObj[i].push({ content: data[i][j] })
       }
    }
    

    Alternatively, you can work with .map().

    let dataObj: { content: any;[key: string]: any }[][] = [];
    
    dataObj = data.map(x => 
      x.map(y => {
        return { content: y };
      })
    );
    

    Sample TypeScript Playground