1

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.

2 Answers 2

2

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;

Sign up to request clarification or add additional context in comments.

Comments

1

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
      })
    ))
  );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.