Antediluvian
Antediluvian

Reputation: 723

rxjs operators in angular

Is there any operator to achieve what the following map tries to do?

this.http.get(this.url)
         .pipe(map(data => {
             let results: object[] = new Array();
             data.forEach(function(d) {
                 let result = d['a'];
                 result['new_index'] = d['b'];
                 results.push(result);
             }
             retrun results;
         }));

d['a'] is an object while d['b'] is a string. The new_index key is new to each result.

Basically the original data contains quite a few fields out of which I only want 2 fields, one being the actual data of the object type, and the other an ID like field. I do not need any other fields. And I need to pull out that object data and insert the ID field into that object.

Upvotes: 1

Views: 337

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39432

You can use the map Operator from Rxjs along with the map method on an array to do this:

Your implementation could be simplified like this:

this.http.get(this.url)
  .pipe(
    map((data: any[]) => data.map(
      (datum: any) => ({ 
        ...datum.a,
        new_index: datum.b
      })
    ))
  );

Upvotes: 1

user3335966
user3335966

Reputation: 2745

I don't understand a little bit Your data structure.

If http.get returns data like:

[{
  a: {...},
  b: '...'
}]

then You just can use:

this.http.get(this.url)
  .pipe(map(({a, b}) => {
    a.new_index = b;
    return a;
  }));

jsfiddle example;

But if Your data is really something like:

[
  [{a: {...}, b: '...'}],
  [{a: {...}, b: '...'}],
]

(as You processing in Your example), so You can use [].map:

this.http.get(this.url)
 .pipe(map(data =>
    data.map(({a, b}) => {
      a.new_index = b;
      return a;
    })
 ));

jsfiddle example;

Upvotes: 2

Related Questions