Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rxjs loop through nested object

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);
like image 602
Pratap A.K Avatar asked Sep 18 '26 21:09

Pratap A.K


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.

like image 122
bryan60 Avatar answered Sep 21 '26 14:09

bryan60



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!