← JavaScript Coding

Get and Set by Path

mediumobjectspathsutility
Asked at
Airtable
Atlassian
Notion
Salesforce
Shopify
Airtable, Atlassian, Notion, Salesforce, Shopify

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.
  • setByPath must 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.

Premium

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
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

4. Improve a function

JS CodingMedium

Camel Case Keys

JS CodingHard

Deep Clone II

JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • Airtable interview
  • Atlassian interview
  • Notion interview
  • Salesforce interview
  • Shopify interview