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
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
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.
In order to ensure that the Poppinss community is welcoming to all, please review and abide by the Code of Conduct.
Poppinss object builder is open-sourced software licensed under the MIT license.