Search code examples
angulartypescriptngrxngrx-entity

Angular ngrx: check is field exists in object


I'm sorry if it's a duplication of any question, however, I can't find a solution to my problem.

I have a selector that getting a big object with a big nesting. And I need to return some value from it. How can I check is fields exist to prevent crashing?

export const getSingleValue = createSelector(
    getEntities,
    (entities) => entities
        .map(item => {
            // need to check is field and oneMoreField, etc. exist
           return item.field.oneMoreField.andMoreField.andHereIs.value || null; 
        })
);

The plan B - wrap returning to try-catch but I think it's not a good option.


Solution

  • Typescript doesn't support an Elvis operator out of the box.

    So some of the options you have:

    Manually check if the property is there, e.g.:

    if(item && item.field && item.field.oneMoreField)
      return item.field.oneMoreField;
    
    // or    
    return item && item.field && item.field.oneMoreField;
    

    Use a proxy object:

    function safe(obj) {
      return new Proxy(obj, {
        get: function(target, name) {
          const result = target[name];
          if (!!result) {
            return (result instanceof Object)? safe(result) : result;
          }
          return safe({});
        }
      });
    }
    return safe(item.field.oneMoreField);
    

    Or with a library, such as Lodash:

    _.get(item, 'field.oneMoreField')