SBB
SBB

Reputation: 8970

lodash map data only if array exists

I have a small function I need to write that takes the values of two objects and stores them into an array which I then merge together for a single array of data.

The issue is that there one of the arrays may not exist so it should just returned an empty array so that the merge wouldn't complain.

let active = _.map(this.modalData.currentExceptions.activeExceptions.active, 'QID');
let future = _.map(this.modalData.currentExceptions.futureExceptions.future, 'QID')
let combined = _.merge(active, future);

In this case, futureExceptions isnt an array in this data set so map throws an undefiend error.

Is there something I can add to this .map will return an empty array if the key / object isn't found?

Upvotes: 3

Views: 677

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38962

You can use _.get. It allows you to set a default when a key resolves to undefined.

let active = _.map(
  _.get(
    this.modalData.currentExceptions.activeExceptions, 'active', []
  ), 
  'QID'
);

let future = _.map(
  _.get(
    this.modalData.currentExceptions.futureExceptions, 'future', []
  ),
  'QID'
)

let combined = _.merge(active, future);

Upvotes: 1

Related Questions