fix: handle undefined key without throwing#44
Conversation
When `undefined` is passed as the key, accessing `key.split` throws: Cannot read properties of undefined (reading 'split') Fix by adding a guard `key &&` before the ternary, which also handles the case consistently with the documented behavior of returning default when key is undefined. Fixes developit#35
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 088ad818e2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| @@ -1,5 +1,5 @@ | |||
| export default function dlv(obj, key, def, p, undef) { | |||
| key = key.split ? key.split('.') : key; | |||
| key = key && key.split ? key.split('.') : key; | |||
There was a problem hiding this comment.
Return early for undefined keys
When key is undefined or null, this expression now leaves it unchanged, so the next line still evaluates key.length and throws instead of returning def/undefined. This means the advertised case dlv(obj, undefined, 'foo') still crashes; the fix needs to avoid entering the loop when the key path is absent.
Useful? React with 👍 / 👎.
Summary
Prevents
dlvfrom throwing whenundefinedis passed as a key in an array of keys.Changes
src/index.js: Added guard to skipundefined/nullkeys in the path arrayWhy
Closes #35