简体   繁体   中英

How do you modify object in array with response from observable RxJs

I am trying to iterate over an array of people and call an api which returns a new age which I will override the age and then merge with dogs array. The code looks like this:

const dogs = [{name:'Chichi', age:2}, {name:'Yayo', age:4}];
const people = [{name:'Mike', age:23}, {name:'John', age:45}];

const modifiedPeople = people.map(person => {        
    getNewAge(person).pipe(map(newAge=> {return person.age = newAge}));

return [...dogs, modifiedPeople];

})

This always returns an empty modifiedPeople . How can I perform this operation with RxJs in ES6

You cant call the async call in the Array.map as it is a synchronous method. It will not wait for async call to complete and moves further which is why you are getting undefined for modifiedPeople and moreover pipe operator returns an Observable which needs to be subscribed for the result.

forkJoin(
  people.map(person =>
    this.getNewAge(person)
      .pipe(map(newAge => ({ ...person, age: newAge })))
  )
)
.subscribe(result => console.log(result));

the result will be your modifiedPeople

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM