Filtering data from JSONArray and assigning it to a new object

34 Views Asked by At

Consider the following example:

const arr1 = [{'a': 'I', 'b': 'M', 'c': 'Q'}]; const arr2 = [{'x': 'C', 'y': 'D', 'z': 'M'}];

// I am getting these arrays from a service call

if (value of key 'z' of arr2 matches with value of key 'b' of arr1) {

// Assign key-value x and y to arr1 object

}

Is it possible with any RxJs operator? I implemented forkJoin and was able to get both arrays from service to component level. However I tried with mergeMap and flatMap also, but was unsuccessful. Seems like, I have to run a nested loop which I am trying to avoid.

1

There are 1 best solutions below

1
On

Well, your question doesn't have any context, so here's an answer that does something like what you've asked for:

forkJoin(
  of([{a: 'I', b: 'M', c: 'Q'}]),
  of([{x: 'C', y: 'D', z: 'M'}])
).pipe(
  map(([[ob1],[ob2]]) => 
    ob1.a == ob2.z? 
    [[{...ob1, x: ob2.x, y:ob2.y}],[ob2]]:
    ([[ob1],[ob2]])
  )
).subscribe(console.log);

If you re-write your question with more detail/context, you can probably get a better answer :)