maybeAdd

Function

Append or replace a value on an object, using a specified key, if the value is not null. This is a very useful companion to the getProp() utility.

Note: object that is passed in is cloned before the property is appended.

Allows for code like:

let model = {
 item: {
   title: 'some example object',
   description: 'this is some longer text',
   type: 'Web Map',
   properties: {
     sourceId: '3ef'
   }
 },
 data: {
   theme: 'orange',
   parcelLayer: {
     primaryField: 'PIN'
   }
 }
};

// Let's extract some details into an object.
const summary = [
 'item.title',
 'item.description',
 'item.missingProp',
 'data.parcelLayer.primaryField'].reduce((acc, prop) => {
  // create the property name... you could do this however...
  let propName = prop.split('.').reverse()[0];
  return maybeAdd(propName, getProp(model, key), acc);
}, {});

// summary =>
// {
//   title: 'some example object',
//   description: 'this is some longer text',
//   primaryField: 'PIN'
// }
  • maybeAdd(key: string, val: any, target: any) : any

Parameters

Parameter Type Default Notes
key Required string

key to use when appending to the object

val Required any

the possibly null value

target Required any

the object to update

Returns

any

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