0

I want to use Rxjs map() method to switch values between two json objects. Or if there are any better rxjs methods I am open to suggestions

For example if I have two json objects:

[{"firstname":"abc","lastname":"bcd"},{"firstname":"xyz","lastname":"zzz"}]

How do I for example switch the values of first name from both json objects in the array as well as the lastnames? I am very new to rxjs!

Thanks!

6
  • 1
    Does your Observable emit {"firstname":"abc","lastname":"bcd"}, then {"firstname":"abc","lastname":"bcd"}, or does it emit [{"firstname":"abc","lastname":"bcd"},{"firstname":"xyz","lastname":"zzz"}] all at once? Commented Aug 1, 2019 at 13:57
  • It emits it all at once currently. Commented Aug 1, 2019 at 14:08
  • 1
    what is the desire output? switch both the firstname and the lastname? Commented Aug 1, 2019 at 14:12
  • So basically switching both JSON objs ? x) Commented Aug 1, 2019 at 14:18
  • Could you please add the desired output to your question. Commented Aug 2, 2019 at 12:11

1 Answer 1

0

In your example, swapping the entire objects will work:

let swapped = observable.pipe(map(([first, second]) => [second, first]));

In older versions of JS (and made a bit verbose on purpose):

function swapPair(arr) {
    var first = arr[0];
    var second = arr[1];
    return [second, first];
}

var swapped = observable.pipe(map(swapPair));

If you want a more generic way to swap properties -- I was about to write something, but really it's been done before:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.