javascripttypescript

Merge objects in javascript while ignoring property values that are undefined (jQuery.fn.extend behavior)


I'm looking for an implementation of jQuery.fn.extend in typescript/javascript. Specifically, I'm interested in the part where it ignores undefined values in the source object.

const obj1 = {
  a: 1,
  b: undefined
};

const obj2 = {
  a: undefined, // Should be ignored.
  b: 100
};

const merged = $.extend(obj1, obj2);

console.log(merged); // {a: 1, b: 100}

The structure of the objects to be merged is not necessarily well-known and one may contain more properties than the other.


Solution

  • You could define a helper function that would create an object with the undefined properties removed:

    const definedProps = obj => Object.fromEntries(
        Object.entries(obj).filter(([k, v]) => v !== undefined)
    );
    

    And then the merge becomes:

    const merged = Object.assign(obj1, definedProps(obj2));
    

    const obj1 = {
      a: 1,
      b: undefined
    };
    
    const obj2 = {
      a: undefined, // Should be ignored.
      b: 100
    };
    
    const definedProps = obj => Object.fromEntries(
        Object.entries(obj).filter(([k, v]) => v !== undefined)
    );
    const merged = Object.assign(obj1, definedProps(obj2));
    
    console.log(merged);