exist.js
If you are tired of those:
// To get `name`, but you do not know whether `employees` and `employees[0]` exist or notconst name = companyemployees && companyemployees0 && companyemployees0name; // To set `name`, but you do not know whether `employees` and `employees[0]` exist or notif companyemployees && companyemployees0 companyemployees0name = 'Benjy'; // To call a method of nested `Object`if companyemployees && companyemployees0 && typeof companyemployees0getName === 'function' var name = companyemployees0;You can try exist.js. Something inspired by the existential operator(?. & ?()) of CoffeeScript, but not the same as it. With exist.js, you can access nested property easily:
// To get `name`, but you do not know whether `employees` and `employees[0]` exist or notconst name = exist; // To set `name`, but you do not know whether `employees` and `employees[0]` exist or notexist; // To call a method of nested `Object`exist;Performance
Maybe you already know lodash's has and get, but exist.js is faster. You can run npm install && node ./perf.js to prove.
Getting Started
Install exist.js as an npm module and save it to your package.json file as a dependency:
npm install exist.js --saveOnce installed, it can now be referenced and used easily:
const exist = ; // => falseAPI
exist.detect(obj, nestedProp)
(Object, String|Array) -> true | Array
To check whether a nested property exists in Object or not. If the nested property is exist, return true. Otherwise, return the path to the property where the value starts missing.
const company = employees: name: 'Benjy' ; // => true // => ['bosses']exist.get(obj, nestedProp[, defaultValue])
(Object, String|Array[, anything]) -> undefined | value
To get a nested property. If this property does not exist, return undefined or defaultValue.
const company = employees: name: 'Benjy' ; exist // => 'Benjy'exist // => undefinedexist // => 18exist.set(obj, nestedProp, value[, createMissing])
(Object, String|Array, anything[, boolean]) -> boolean
To set a value to nested property. If success, return true. Otherwise, false.
If createMissing is true, exist.set will create plain objects and replace missing parts with them, so the value will be set correctly and return true.
const company = employees: {}; exist // => trueexist // => false, for `stockholders` does not exist // After this call, company is `{ ..., stockholders: { 0: { name: 'Benjy' } } }`existexist.invoke(obj, nestedMethod)
(Object, String|Array) -> Function
To get a nested method, or return NOOP(function() {}) if this property does not exist.
const company = employees: name: 'Benjy' { console; } ; exist'Bob' // => 'Nice to meet you, Bob!'exist'Bob' // => Nothing will happenLicense
MIT