Skip to content

A convenience class to create an object with dynamic properties

License

Notifications You must be signed in to change notification settings

poppinss/object-builder

Repository files navigation

@poppinss/object-builder


gh-workflow-image npm-image license-image

Installation

Install the package from the npm package registry.

# Npm
npm i @poppinss/object-builder

# Yarn
yarn add @poppinss/object-builder

# Pnpm
pnpm add @poppinss/object-builder

Usage

The ObjectBuilder is a convenience class to create an object with dynamic properties. Consider the following example, where we wrap our code inside conditionals before adding the property b to the startingObject.

const startingObject = {
  a: 1
  // Add "b", if it exists
  ...(b ? { b } : {})
}

// OR
if (b) {
  startingObject.b = b
}

Instead of writing conditionals, you can consider using the Object builder fluent API.

import { ObjectBuilder } from '@poppinss/object-builder'
const builder = new ObjectBuilder({ a: 1 })

const plainObject = builder.add('b', b).toObject()

By default, only the undefined values are ignored. However, you can also ignore null values.

import { ObjectBuilder } from '@poppinss/object-builder'

const ignoreNullValues = true
const builder = new ObjectBuilder({ a: 1 }, ignoreNullValues)

Following are the available methods on the ObjectBuilder class.

builder.remove(key)
builder.has(key)
builder.get(key)
builder.add(key)

builder.toObject() // get plain object

Contributing

One of the primary goals of Poppinss is to have a vibrant community of users and contributors who believes in the principles of the framework.

We encourage you to read the contribution guide before contributing to the framework.

Code of Conduct

In order to ensure that the Poppinss community is welcoming to all, please review and abide by the Code of Conduct.

License

Poppinss object builder is open-sourced software licensed under the MIT license.

About

A convenience class to create an object with dynamic properties

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published