Set Default Values For Nested Objects – Default Composer

Category: Javascript | July 10, 2023
Author:aralroca
Views Total:55 views
Official Page:Go to website
Last Update:July 10, 2023
License:MIT

Preview:

Set Default Values For Nested Objects – Default Composer

Description:

Default Composer is a tiny JavaScript library that allows you to set default values for nested objects in an efficient and simple way.

It replaces empty strings, arrays, objects, null, or undefined values in an existing object with predefined default values. This can significantly simplify your programming logic and minimizes the amount of code you need to set these defaults.

How to use it:

1. Install and import the Default Composer.

# Yarn
$ yarn add default-composer
# NPM
$ npm i default-composer
import { defaultComposer } from "default-composer";

2. Define your default values object:

const defaults = {
  name: 'John',
  age: 30,
  address: {
    street: 'Main street', 
    city: 'New York'  
  }
}

3. Call the defaultComposer() function and pass in your default values object and the object you want to apply defaults to. The defaultComposer() fucntion accepts one or more objects as arguments and returns a new object with the default values duly applied. The first argument should be an object containing the default values. Subsequent arguments should be the objects you wish to set default values for. Should a property in a provided object be empty, null, or undefined, and the corresponding property in the default object is not empty, null, or undefined, the default value will be used.

const result = defaultComposer(defaults, originalObject);

4. The library also provides a setConfig component to set isDefaultableValue option for defaultComposer() function.

import { defaultComposer, setConfig } from "default-composer";
setConfig({
  isDefaultableValue({ key, value, defaultableValue }) {
    return (
      defaultableValue || (typeof value === "string" && value.trim() === "")
    );
  },
});
const defaults = { example: "replaced", anotherExample: "also replaced" };
const originalObject = { example: "   ", anotherExample: null };
const result = defaultComposer<any>(defaults, originalObject);
console.log(result); // { example: 'replaced', anotherExample: 'also replaced' }

5. Merge arrays.

const defaults = {
  hobbies: ["reading"],
};
const object = {
  hobbies: ["running"],
};
setConfig({ mergeArrays: true});
defaultComposer<any>(defaults, object))

Changelog:

v0.5.0 (07/10/2023)

  • feat: add config to merge arrays

You Might Be Interested In:


Leave a Reply