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.
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}) ));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With