Reputation: 252
I have 2 differents list of objects and i want to combine them together for exemple:
listObj1 = [{name:'bob 1'}, {name:'bob 2'}]
listObj2 = [{pseudo:'Bob Razowski'}, {pseudo:'sponge bob'}]
result = [
{name:'bob 1', pseudo:'Bob Razowski}
{name:'bob 2', pseudo:'sponge bob'}
]
Can i do that with rxjs and how or if you have a better solution let me know
const characters = [];
const name$ = Observable.from(this.nameList)
.map(item => {
return {'name': item};
})
const pseudo$ = Observable.from(this.pseudoList)
.map(item => {
return {'pseudo': item};
})
Observable.zip(name$, pseudo$).subscribe(result => {
let char= {};
if(result.length > 1) {
char['name'] = result[0];
char['pseudo'] = result[1];
characters.push(char)
}
});
I started something like that but when i see the result, i can do it without rxjs. My question is more if it exists an other operator to do that.
thank
Upvotes: 1
Views: 1027
Reputation: 14199
Well, you can do it with RxJS, but there is no obvious reason to do so, looking at your code snippet. One reason to do it reactively would be that you had really long lists and wanted to let the combination happen on (hypothetical) multiple threads. But in JavaScript that's not really practical, so for...of
or Array.map
are the right choices for this kind of task.
Anyhow, the RxJS solution would look like this:
zip(
from(listOb1),
from(listObj2)
).pipe(
map(([one, two]) => Object.assign({}, one, two)),
toArray()
)
Convert both lists into Observable streams with from
, then zip
them together and map
each pair onto a new object using Object.assign
. Collect the objects with toArray
and done.
Upvotes: 2