Skip to content

Giancarl021/fill-object

Repository files navigation

fill-object

Fill deep properties missing in an object based on a default object

Similar projects

Why?

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.

Installation

You can get this package on NPM.

Usage

Importing

CommonJS:

const fillObject = require('fillObject');

ES Modules:

import fillObject from 'fillObject';

Calling

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
): T
  • partialValue (Partial<T>): The partial value to be filled;
  • defaultValue (T): The default value to fill the partial value;
  • overwriteOnTypeMismatch (boolean): If true, the value will be overwritten if the types do not match. Defaults to false.

Examples

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 }

Tests

This library uses Jest for testing. To run the tests, use the following command:

yarn test

About

Fill deep properties missing in an object based on a default object

Resources

License

Stars

Watchers

Forks