Get and Set by Path
Problem statement
Implement getByPath and setByPath, common utilities used in form libraries, config systems, and state updates.
Path Format
Support dot paths and bracket indexes:
getByPath(user, 'profile.name');
getByPath(user, 'posts[0].title');
Requirements
getByPath(obj, path, defaultValue)returns the value at path or default value when missing.setByPath(obj, path, value)returns a new object with the path updated.setByPathmust not mutate the original object.- Create missing objects/arrays along the path.
- Numeric path segments should create arrays when the next container is missing.
Requirements & constraints
- Do not mutate the original object.
- Support dot paths and numeric bracket indexes.
- Return default value only when the path is missing, not when the value is falsy.
How to approach Get and Set by Path
The strategy an interviewer expects you to reach for.
Get/set by path is lodash get/set: walk a.b[0].c safely. Naive move eval the path, or assume every segment exists. Where it breaks Missing segments should return default on get. Set must create intermediate objects/arrays based on whether the next segment looks like an index. The fix Normalize brackets to dots, split segments. get walks until nullish. set creates {} or [] for missing parents, then assigns the leaf. Remember: Parse once; create the right container type on the way down for set. Say this in the interview: I'd normalize the path into segments, walk safely for get with a default, and for set create intermediate objects or arrays depending on the next segment.
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Runnable editor with the hidden test suite
- Progressive hints that unlock as you get stuck
- Senior-level reference solution with a line-by-line walkthrough
Already a member? Log in to open the workspace.