Reputation: 10922
I have created an observable from a JSON array, I want to add new values for each element inside the array, and I need to do it based on the index of the element.
So far I'm only able to add same key-value for all the elements. Is there a way to introduce index into map function? So for example I can say that for the first element "is_leader" is true, and for all the others it's false.
Code so far:
this.dataSubscription = this.dataService.getTestData().subscribe(
res => {
this.allData = res.map(data => {
data['is_leader'] = true; // Here I would like a condition
return data;
});
}
);
Working in Angular 2.
Upvotes: 0
Views: 7122
Reputation: 238
Can you try this?
this.dataSubscription = this.dataService.getTestData().subscribe(res => this.allData = res.map((data, index) => {
data['is_leader'] = index === 0;
return data;
})
);
Upvotes: 5