0

I have following array, that I need to transform before inserting into database. Right now my data are looking like this:

enter image description here

And I would like to save the data in this format:

enter image description here

So far I have tried this code, but with no luck:

const buildTvTimeline = (r: Data) =>
{
   const meta = get(r, ["meta", "tv"], []);

   return Object.keys(meta).map((index: any) =>
   {
      const game = meta[index].game;
      const tile = meta[index].tile;
      const dates = meta[index].dates;

      const data = dates.map((r: any) => ({ ...r, tile: tile, game: game }));

           return data;
       });
 }
 const timeline = buildTvTimeline(r);
        
 const data = Object.keys(timeline).map((index) => 
 {
      return timeline[index];
 });

 set(r, ["timeline", "tv"], data);

Any ideas what can I do to transform the format of the first array into the format of the second array?

Thank you in advance

AdamSulc
  • 296
  • 3
  • 14
  • 5
    [`array.flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) is what you are looking for. – Reyno Jul 09 '20 at 09:45
  • @theblackgigant gonna accept your answer as soon as I can. Thanks – AdamSulc Jul 09 '20 at 09:49
  • 3
    Does this answer your question? [Merge/flatten an array of arrays](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) – Danila Jul 09 '20 at 09:50

1 Answers1

3

You can use array.flat() to turn a multidimensional into a flat array.

Since i can't use your data i created my own.

const tv = [
  [
    {
      a: "a"
    },
    {
      b: "b"
    }
  ],
  [
    {
      c: "c"
    },
    {
      d: "d"
    }
  ]
];

const tvFlat = tv.flat();

console.log(tvFlat);
Reyno
  • 3,546
  • 10
  • 21