What is undefsafe?
The undefsafe package is a utility for safely accessing deeply nested properties of an object. It allows developers to query properties without worrying about intermediate properties being undefined or null. This can be particularly useful in situations where the structure of an object might be unpredictable or when dealing with JSON objects returned from an API.
What are undefsafe's main functionalities?
Safe property access
This feature allows for the safe querying of nested properties. If any property in the path is undefined, undefsafe will return `undefined` instead of throwing an error.
const undefsafe = require('undefsafe');
const obj = { a: { b: { c: 'd' } } };
console.log(undefsafe(obj, 'a.b.c')); // 'd'
console.log(undefsafe(obj, 'a.x.c')); // undefined
Setting deeply nested values safely
Undefsafe can also be used to set a value at a deeply nested path within an object. If any part of the path does not exist, it will be created.
const undefsafe = require('undefsafe');
let obj = {};
undefsafe(obj, 'a.b.c', 'd');
console.log(obj.a.b.c); // 'd'
Other packages similar to undefsafe
lodash.get
Lodash's get function offers similar functionality for safely accessing nested object properties. Unlike undefsafe, lodash.get is part of the larger lodash library, which provides a wide range of utilities for working with arrays, numbers, objects, strings, etc. Lodash.get does not support setting values.
dot-prop
Dot-prop is another package that allows for getting and setting properties on objects using dot-path notation. It supports both getting and setting values, similar to undefsafe. However, dot-prop offers additional features such as deleting properties and checking if an object has a certain property.