maybePush

Function

Append a value to an array, if the value is not null. This is a very useful companion to the getProp() utility.

Note: the array that is passed in is cloned before being appended to.

Allows for code like:

 // example object
let model = {
 item: {
   id: 'c00',
   title: 'some example object',
   description: 'this is some longer text',
   type: 'Web Map',
   properties: {
     sourceId: '3ef'
   }
 },
 data: {
   theme: 'orange',
   parcelLayer: {
     itemId: '7ca',
     primaryField: 'PIN'
   }
 }
};
// lets pluck some id's into an array...
maybePush(getProp(model, 'item.properties.sourceId'), []);
// > ['3ef']

// now try to get a value from a property that is missing...
maybePush(getProp(obj, 'item.properties.childId'), []);
// > []

// easily pluck values via property paths
const summary = [
 'item.id',
 'item.properties.sourceId',
 'item.properties.childId',
 'data.parcelLayer.itemId'].reduce((acc, prop) => {
  return maybePush(getProp(model, key), acc);
}, []);

// summary => ['c00', '3ef', '7ca']

  • maybePush(val: any, target: any[]) : any[]

Parameters

Parameter Type Default Notes
val Required any

the possibly null value

target Required any[]

the array to add the value to

Returns

any[]

Function defined in common/src/util.ts:232