lodash map data only if array exists

Viewed 505

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?

1 Answers

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);
Related