2

to all! I have the following data:

const datas = [
  {
    first: 'id',
    secondLevel: [
      {
        second: 'id2',
        thirdLevel: ['a', 'b', 'c']
      },
      ...
    ]
    ...
  }
  ...
]  

My goal is to create all possible associations with the data of the 3 levels

for example

[
  { 
    first: 'id', 
    second: 'id2', 
    third: 'a' 
  },
  { 
    first: 'id', 
    second: 'id2', 
    third: 'b' 
  },
  ...
]

I'm currently doing it with a foreach in a foreach in a foreach and it's horrible I'm sure I can do it really better.

Somebody can help me ? Thanks !

Carbonnel
  • 21
  • 1

1 Answers1

1

You could take a recursive approach and get first the value part and the array. Then iterate the array and get either a value or object from the array for flattaning.

Finally add the value part the the rest and get a flat array of objects.

This approach works for unknow depth. Mabe a good idea is to omit a key name with a Level suffix, which would omit slicing.

const
    flat = object => {
        let value, array;
        Object.entries(object).forEach(([k, v]) => {
            if (Array.isArray(v)) array = { k: k.slice(0, -5), v };
            else value = { [k]: v };
        });
        return array.v.flatMap(o => o && typeof o === 'object'
            ? flat(o).flatMap(q => ({ ...value, ...q }))
            : { ...value, [array.k]: o }
        );

    },
    data = [{ first: 'id', secondLevel: [{ second: 'id2', thirdLevel: ['a', 'b', 'c'] }] }],
    result = data.flatMap(flat);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thank you Nina. Your answer was very helpful. And I learned a lot of new things from it. I did not even know that there was an array method called `flatMap`. lol – Tom Bombadil Apr 14 '21 at 18:19