Search code examples
javascriptclonehelper

How to get a subset of a javascript object's properties excluding undefined or null properties


I can have different version of an object:

myObject1 = { 
  color: 'red',
  size : 'big',
  name : 'Beautiful red',
  count: 2
};

myObject2 = { 
  color: 'blue',
  name : 'Awesome blue',
  count : null
};

I need a helper to keep only value i want and which exist :

function myHelper() {
   ?????
}


myHelper(myObject1, ['color','size','count']) // => { color: 'red', size : 'big', count:2}
myHelper(myObject2, ['color','size','count']) // => { color: 'blue'}

Anyone already created it ?


Solution

  • Convert the object to entries and filter by:

    • Object property (key) exists in the desired key list (props)
    • Value (val) is not null.

    const myObject1 = { 
      color: 'red',
      size : 'big',
      name : 'Beautiful red',
      count: 2
    };
    
    const myObject2 = { 
      color: 'blue',
      name : 'Awesome blue',
      count : null
    };
    
    function myHelper(obj, props) {
      return Object.fromEntries(Object.entries(obj)
        .filter(([key, val]) => props.includes(key) && val != null));
    }
    
    console.log(myHelper(myObject1, ['color','size','count']));
    console.log(myHelper(myObject2, ['color','size','count']));
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    If you want to optimize this, you can change the "array includes" to a "set has" check via:

    const myHelper = (obj, props) => (pSet => Object.fromEntries(Object.entries(obj)
        .filter(([key, val]) => pSet.has(key) && val != null)))
    (new Set(props));