2

I have an existing codebase that uses AngularJS, Redux and Underscore. In that codebase I have the following code:

const selectedBroker = _.findWhere(state.brokers, { brokerId: action.payload });
  return state.merge({
    selectedBroker,
    selectedBrokerId: action.payload,
  });

I want to convert it to an es6 Method. I think the find(), would be suitable, but don't know how. Could you help me a little bit? Thanks!!

Also it is not in the scope of this task but I see more underscore methods here. Like _.reject, _.contains, _.map. Could you also convert that in the context similar to the above code example.

  • You could use `babel-core` to generate an AST, transform the nodes pointing to `_.method` calls and compile the AST back to code. To use `find` in place of findWhere, the following might do `selectedBroker = state.brokers.find(({brokerId}) => brokerId === action.payload)` – Moritz Roessler Oct 24 '18 at 19:10

1 Answers1

0

It will be just like below, array.find will return the first matching element in the array.

let selectedBroker = state.brokers.find(broker => broker.brokerId == action.payload);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
  • Thank you. I have a question. In this case, you used `t=>t.brokerId`. Could you explain the logic? That part of the code always frustrates and confuse me. I mean what is the `t`? –  Oct 24 '18 at 19:05
  • 1
    @DimitrisEfstathiadis This might make more sense: `state.brokers.find(broker=>broker.brokerId == action.payload);` It's just the variable name assigned to the entry each loop. – lux Oct 24 '18 at 19:06
  • 1
    t is the object where t.brokertId is the value that brokerId holds which will be compared with action.payload if it matches find will return the matching element – Sajeetharan Oct 24 '18 at 19:06
  • Thank you both guys. That helped a lot.. –  Oct 24 '18 at 19:08
  • @DimitrisEfstathiadis mark if the answer helped – Sajeetharan Oct 24 '18 at 19:09