Reputation: 723
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
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
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;
}));
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;
})
));
Upvotes: 2