Rxjs loop through nested object

Viewed 1394

RxJS how to get specific attribute values from nested array of objects

const obj = {
      name: 'campus',
      buildings: [
        {
          name: 'building',
          floors: [
            {
              name: 'floor'
            }
          ]
        }
      ]
    };

Is there a way to get names in RxJS. Basically I need output as [campus, building, floor]

Observable.of(obj).map((res) => res.name).subscribe((val) => console.log(val));

I know how to do this without using RxJS. But I would like to know how to do using RxJS. Thanks in advance

Currently I'm doing something like below

const names = [];
    names.push(obj.name);
    obj.buildings.forEach((building) => {
      names.push(building.name);
      building.floors.forEach((floor) => {
        names.push(floor.name);
      });
    });
    console.log(names);
1 Answers

this should work:

getNames(obj) {
    const names = [];
    names.push(obj.name);
    obj.buildings.forEach((building) => {
      names.push(building.name);
      building.floors.forEach((floor) => {
        names.push(floor.name);
      });
    });
    return names;
}

Observable.of(obj).map((res) => this.getNames(res)).subscribe((val) => console.log(val));

You're changing one value into another, simplest like this. There isn't a special reactive way of acting on a single value. Reactive methods are for acting on streams of values over time, as it stands, you're operating on a single value in a stream, so best to treat it like one instead of jumping through hoops to try and do things "in the reactive way". If you were trying to collect the "name" properties from a series of objects over time, then that would be a different story, you could use reduce or scan in that case.

Related