javascriptjavascript-objectsspread-syntax

Condition Spread based on Object props


I'm looking for way to remove empty or null props, on my example obj2, I want to avoid copying the birthPlace property or any other prop that comes empty.

const obj1 = { firstName: 'Foo', age: 22 };

const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = { ...obj1, ...obj2 };

Desired result:

{firstName: 'Foo', age: 22, lastName: 'Bar', gender: 'M'}

Is it possible using Conditional Objects props using Spread Operators in javascript?

const updateUserObj = {
  ...(obj1 !== check here<hasPropEmpty> && obj2)
}

Solution

  • Using Object#entries you get the key-value pairs of an object, then, using Array#filter you iterate over these pairs to filter out the ones with empty values. Then, using Object#fromEntries you construct back the resulting pairs to an object.

    const filterProps = (obj = {}) => 
      Object.fromEntries(
        Object.entries(obj).filter(([key, value]) => 
          value !== null && value !== undefined && value !== ''
        )
      );
    
    const obj1 = { firstName: 'Foo', age: 22 };
    const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };
    
    const newObj = { ...filterProps(obj1), ...filterProps(obj2) };
    
    console.log(newObj);