1

I'm filtering data from 2 objects that I receive from an API. I need to have a ['data', 'data2', 'dat2'], but when I get the data I'm receiving like this:

[ ['data'], ['data2', 'dat3'] ] 

I need to transform that into:

['data', 'data2', 'dat2']

This is how I'm filtering the data:

    const filteredData = response.data.map((value) => {
      const data = value.students.map((value) => {
        return value.studentId;
      });

      return filteredData;
    });

If you are wondering how is the data set:
Data:

[
  {
    id: 1,
    students: [
     {id: 1, studentId: 1829},
     {id: 2, studentId: 4329}
    ]
  },
  {
    id: 2,
    students: [
     {id: 3, studentId: 1429},
     {id: 6, studentId: 329}
    ]
  }
]
Nilton Schumacher F
  • 814
  • 3
  • 13
  • 43

1 Answers1

3

Use flat to flatten nested arrays

[ ['data'], ['data2', 'dat3'] ].flat()

And flatMap(x => x.students) to flatten arrays within more complex object structures

const data = [
  {
    id: 1,
    students: [
     {id: 1, studentId: 1829},
     {id: 2, studentId: 4329}
    ]
  },
  {
    id: 2,
    students: [
     {id: 3, studentId: 1429},
     {id: 6, studentId: 329}
    ]
  }
]

const flattened = data.flatMap(x => x.students)

// Output:
[
    {
        "id": 1,
        "studentId": 1829
    },
    {
        "id": 2,
        "studentId": 4329
    },
    {
        "id": 3,
        "studentId": 1429
    },
    {
        "id": 6,
        "studentId": 329
    }
]
Martin Devillers
  • 17,293
  • 5
  • 46
  • 88