0

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.

1
  • The provided dataObj was incorrect, especially for the second array item. Kindly revise and update. Thanks. Commented Aug 6, 2022 at 8:30

1 Answer 1

1
  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

Sign up to request clarification or add additional context in comments.

2 Comments

GREAT! the first way (which I understand better : ) works perfectly, like a charm! Thanks Yong Shun!
@Nicola I would suggest you spend some time learning the second approach. Writing less code reduces leaves room for fewer bugs, reduces our cognitive load, and can communicate intentions more clearly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.