简体   繁体   中英

Filter nested collections using Rxjs

I need to filter the following json data structure using Rxjs operators,

consider the following example, we have list of hotels and each hotel as rooms underneath it, we need to get all hotels that have available rooms in it,

so consider the following input as:

 var hotels = [ { "hotel": "hotel 1", "rooms": [ { "name": "room 1", "flexible": true }, { "name": "room 2", "flexible": false } ] }, { "hotel": "hotel 2", "rooms": [ { "name": "room 1", "flexible": false }, { "name": "room 2", "flexible": false } ] } ]; 

and the desired output should be as the following:

  var availableRooms = [ { "hotel": "hotel 1", "rooms": [ { "name": "room 1", "flexible": true } ] } ]; 

so How can I apply this in Rxjs?

Thanks

Are you sure that we need a RxJx?

function isAvailable(room) { return room.flexible };
hotels
  .map(hotel => ({ ...hotel, rooms: hotel.rooms.filter(isAvailable) }))
  .filter(hotel => hotel.rooms.length);

If hotel goes one by one - then use the same approach but with RxJs operators.

Edited
Solution with RxJS

function isAvailable(room) { return room.flexible };
from(hotels).pipe(
  map(hotel => ({ ...hotel, rooms: hotel.rooms.filter(isAvailable) })),
  filter(hotel => hotel.rooms.length),
  toArray(),
).subscribe(console.log)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM