Max R
Max R

Reputation: 5

How to filter an object array of another object array in TypeScript?

I know how to filter bookings by b.building.id here:

bookings.filter(b => b.building.id == this.filter.buildingId);

But how to filter the bookings object array if the b.modules is a also an array. Here's my failed attempt:

bookings.filter(b => b.modules.programme.facultyId == this.filter.facultyId);

And another failed attempt:

bookings.filter(b => {
  for (let module of b.modules) {
    module.programme.facultyId == this.filter.facultyId;
  }
});

Update:

Here's an example of bookings result in JSON:

[
  {
    "id": 2,
    "semesterId": 1,
    "room": {
        "capacity": 17,
        "code": null,
        "building": {
            "id": 5,
            "name": "Faculty of Science"
        },
        "id": 15,
        "name": "FSB 1.10"
    },
    "building": {
        "id": 5,
        "name": "Faculty of Science"
    },
    "bookDate": "2020-11-10T00:00:00",
    "timeSlots": [
        {
            "id": 1,
            "startTime": "1900-01-01T07:50:00",
            "endTime": "1900-01-01T08:40:00"
        },
        {
            "id": 2,
            "startTime": "1900-01-01T08:50:00",
            "endTime": "1900-01-01T09:40:00"
        }
    ],
    "modules": [
        {
            "id": 5,
            "name": "Computer Systems and Information Technology",
            "code": "SS-1202",
            "lecturers": [
                {
                    "id": 4,
                    "name": "Lim",
                    "title": "Dr."
                }
             ],
            "programme": {
                "id": 1,
                "name": "Computer Science",
                "shortName": null,
                "facultyId": 1
            }
        }
    ]
  }
]

Upvotes: 0

Views: 115

Answers (3)

Mahesh
Mahesh

Reputation: 147

Here is the syntax:

var result = bookings.filter(b => b.modules.filter(m => m.programme.facultyId === b.facultyId));

Upvotes: 0

Tejeshree
Tejeshree

Reputation: 962

bookings.filter(b => b.modules.filter(module => module.programme.facultyId == this.filter.facultyId));

and if module.programme.facultyId is unique you can use:

bookings.filter(b => b.modules.find(module => module.programme.facultyId == this.filter.facultyId));

Upvotes: 1

Ganesh
Ganesh

Reputation: 6016

Try like this

There are two things might be missing, first second filter is not returning after the filter and in some cases it may miss the this reference.

const that = this;

bookings.filter(b => {
  return b.modules.filter(module.programme.facultyId == that.filter.facultyId)
});

Upvotes: 0

Related Questions