Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
transporter_room_3 Avatar asked Mar 04 '23 20:03

transporter_room_3


1 Answers

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);

This solution uses Object.fromEntries which is rather new, but it is easy to polyfill

Object.fromEntries = arr => Object.assign({}, ...arr.map( ([k, v]) => ({[k]: v}) ));
like image 70
trincot Avatar answered Mar 16 '23 00:03

trincot