Flattening conditional nested lists to a single flat list

Viewed 430

Lodash Flatten nested lists.

I have a function in my Typescript script, where I convert some objects.

Unfortunately, some of the objects are nested, so the return type will sometimes be a nested list.

const values: (IRobotics | IRobotics[][])[] //this is an interface type i described

I used the LoDash FlatMap function to try to flatten it out, but it still gives one nested level for each of the objects.

When the response comes, it only removes the outer list.

I tried using the _.flatMap() function initially, const parsedValues = _.flatMap(values) as IRobotics[];

however The values within the nested lists, is still nested one level too deep (see image for example).

The types are correct, but i just want a single list of objects and not a nested list (which happens with the examples where it is IRobotics[][])

Anybody has a nice solution to flatten a conditional two-layer array from here?

First two lists are the nested ones the rest is parsed correctly

Entire function for reference. The values attribute is where the initial values are returned

  static createFromeData(item: EveryMatrix) {
    const values = Object.entries(item).map(entry => {
      return this.createFromEntry(entry);
    });
    const nestedValues = values.filter(entry => Array.isArray(entry));
    const parsedValues = _.flatMap(values) as IRobotics[];
    const IRobotics = new IRoboticsEveryMatrix(parsedValues);
    return IRobotics;
  }
1 Answers

Use Array.flatMap() instead of Array.map():

const values = Object.entries(item).flatMap(entry =>
  this.createFromEntry(entry)
);

And if you're correct environment doesn't support it, use _.flatMap():

const values = _.flatMap(Object.entries(item), entry =>
  this.createFromEntry(entry)
);

If you want to flatten an array of arrays (because you need to nested list for nestedValues), you can use Array.flat() or _.flatten():

const parsedValues = values.flat as IRobotics[];

Or

const parsedValues = _.flatten(values) as IRobotics[];
Related