Safe nested object access utility for JavaScript/TypeScript. Never crash from Cannot read property of undefined again.
- Simple: One-liner API
- Fast: Minimal overhead
- Safe: Automatic null/undefined checks
- Flexible: String or array path support
- Zero dependencies
- Universal: Works in Node.js and browsers
- TypeScript support: Full type definitions
npm install secure-nestedimport safeGet from "secure-nested";
const user = {
profile: {
name: "Ali",
settings: { theme: "dark" },
},
};
// Safe access
safeGet(user, "profile.name", "Guest"); // 'Ali'
safeGet(user, "profile.age", 0); // 0 (default value)const data = {
users: [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
],
};
safeGet(data, "users.0.name"); // 'Alice'
safeGet(data, "users.3.name", "Unknown"); // 'Unknown'const obj = { a: { b: { c: "value" } } };
safeGet(obj, "a.b.c"); // 'value'
safeGet(obj, ["a", "b", "c"]); // 'value'import { safeSet } from "secure-nested";
const obj = {};
safeSet(obj, "user.profile.name", "Ali");
safeSet(obj, "items.0.value", "test");import { safeDelete } from "secure-nested";
const obj = { a: { b: "value", c: "keep" } };
safeDelete(obj, "a.b");import { safeHas } from "secure-nested";
const obj = { user: { id: 1, name: "Ali" } };
safeHas(obj, "user.name"); // true
safeHas(obj, "user.email"); // falseobj- Object to accesspath- Property path (string or array)defaultValue- Default value if not found- Returns: Found value or default
obj- Object to modifypath- Property pathvalue- Value to setcreateMissing- Create missing objects (default: true)- Returns: Success boolean
obj- Object to modifypath- Property path- Returns: Success boolean
obj- Object to checkpath- Property path- Returns: Exists boolean
Contributions, issues and feature requests are welcome! Feel free to check issues page.
MIT
Give a ⭐ if this project helped you!