@lessworkjs/optional
v1.0.1
Published
Optionally load object parameters
Downloads
292
Readme
Optional
Optionally load object parameters. Return the parameter or null.
Idea based off the Laravel optional helper.
Install
npm i @lessworkjs/optional
Example
const optional = require('@lessworkjs/optional');
const users = [{
name: 'Jane',
}, {
name: 'John',
address: {
street: '101 Main St.',
},
}];
console.log(optional(users[0].address).street);
// null
console.log(optional(users[1].address).street);
// 101 Main St.
You can also use an optional callback:
const results = optional(users[0], user => ({
name: user.name,
address: {
street: '202 Main St.',
},
}));
console.log(results)
/**
* {
name: 'John',
address: {
street: '202 Main St.',
},
}
*/