is there a way to dynamically apply array mappers in TypeScript?

Viewed 95

I need help. I'm trying to get data from an array but every time I add a new group filter (I'm working with a custom Kendo grid) what I receive is a nested array and if I want to get those data I need to add a map method on the new 'items' array. The problem is that I don't have only one group filter but I have too much of them. What can I do?

So every time I have to add another map method on items array and this is not very comfortable. There is a solution to my problem? I can get easily the number of the group filter.

2 Answers

You can use flatMap convert e.g. [ [1, 2], [3, 4] ] to [1, 2, 0, 3, 4, 0] for arr.flatMap(v => [...v, 0]). In your case, this should have the same result:

const temp = this.result.data
    .flatMap(x => x.array)
    .map(y => y.selections)

This makes your code a lot more readable and easier to maintain and add to.

If you actually want to dynamically add map functions, you can do something like this:

const maps = [
    x => x.array,
    v => [v, v * 11],
    v => [v, -v],
    v => `num: ${v}`,
];

const data = [
    { array: [1, 2] },
    { array: [3] },
];

const temp = maps.reduce((data, map) => data.flat().map(map), data);
console.log(temp);

You could remove the forEach by replacing the first map as so:

this.result.data.forEach((x)=>{
  this.selections += x.array.map((y)=> y.selections)
})

It would help to have an example of what this.result and this.selections might contain

Related