Truy cập property lồng sâu (deep nested) dễ gây lỗi Cannot read property of undefined. Giải pháp:
1. Lodash _.get() (khuyên dùng cho dynamic path)
const _ = require('lodash');
let obj = { a: { b: { foo: 'test' }, c: 2 } };
console.log(_.get(obj, 'a.b.foo')); // 'test'
console.log(_.get(obj, 'a.c')); // 2
console.log(_.get(obj, 'a.test')); // undefined
console.log(_.get(obj, 'a.test.x')); // undefined (không throw)
2. Custom getProp (no dependency)
const getProp = (object, path) => {
if (path.length === 1) return object[path[0]];
if (path.length === 0) throw new Error('Empty path');
if (object[path[0]]) return getProp(object[path[0]], path.slice(1));
return undefined;
};
console.log(getProp(obj, ['a', 'b'])); // { foo: 'test' }
3. Optional Chaining ?. (ES2020 — Native, best cho static path)
obj?.a?.b?.foo; // 'test' hoặc undefined
So sánh
| Method | Dynamic path string | Static path | Dependency |
|---|---|---|---|
| _.get | ✓ | ✓ | Lodash |
| Custom getProp | ✓ | ✗ (array) | None |
| Optional chaining | ✗ | ✓ | None (modern) |