Fill deep properties missing in an object based on a default object
- Lodash/defaultsDeep - Lodash function;
- defaults - NPM package;
This package is a simple and lightweight alternative to the Lodash function, to fill an partial object with a default value. This package is made specifically to deal with nested options objects, where a schema must be followed, so, as a side-effect, any property that is not in the schema will be removed.
You can get this package on NPM.
CommonJS:
const fillObject = require('fillObject');ES Modules:
import fillObject from 'fillObject';The fillObject function require two parameters and accepts a third optional parameter:
export = function fillObject<T extends {}>(
partialValue: Partial<T>,
defaultValue: T,
overwriteOnTypeMismatch: boolean = false
): TpartialValue (Partial<T>): The partial value to be filled;defaultValue (T): The default value to fill the partial value;overwriteOnTypeMismatch (boolean): Iftrue, the value will be overwritten if the types do not match. Defaults tofalse.
const defaultOptions = {
a: 1,
b: 2,
c: 3
};Usual filling:
const options = fillObject({ a: 10 }, defaultOptions);
console.log(options);
// -> { a: 10, b: 2, c: 3 }Removing extra properties:
const options = fillObject({ a: 10, d: 4 } as any, defaultOptions);
console.log(options);
// -> { a: 10, b: 2, c: 3 }Type mismatch default behavior:
const options = fillObject({ a: '10' } as any, defaultOptions);
console.log(options);
// -> { a: '10', b: 2, c: 3 }Type mismatch with overwriteOnTypeMismatch set to true:
const options = fillObject({ a: '10' } as any, defaultOptions, true);
console.log(options);
// -> { a: 1, b: 2, c: 3 }This library uses Jest for testing. To run the tests, use the following command:
yarn test