Follow a dotted path through a JSON object.
What to build
A small tool that finds a value deep inside data, without crashing when part of the path is missing.
Requirements
- The first line is a JSON value.
- Each later line is a path, such as
user.nameorlist.0.id. - For each path, print the value at that path with
JSON.stringify. - If the path leads nowhere, print
(missing). - A value of
null,0,falseor""exists, so print it.
Input
A line of JSON, then from 1 to 50 paths.
Output
One line per path.
Constraints
Keys contain no dots.
Example
Input:
{"user":{"name":"Mitu","age":0}}
user.name
user.age
user.phone.number
Output:
"Mitu"
0
(missing)
Why it works
reduce carries the current value down the path, and ?.[key] stops safely as soon as a step is missing. Testing only for undefined means that falsy values such as 0 are still reported as real answers.
Examples
Example 1 · Input
{"user":{"name":"Mitu","age":0}}
user.name
user.age
user.phone.number
Expected output
"Mitu" 0 (missing)
Example 2 · Input
{"list":[{"id":7}]}
list.0.id
list.1.id
Expected output
7 (missing)
Hints
Hint 1
split(".") gives the keys, and reduce can walk down one key at a time.
Hint 2
reduce((value, key) => value?.[key], data) stops safely at anything missing.
Hint 3
Compare the result with undefined. A value such as 0, false or an empty string is a real answer.
Solution
Show one correct solution (try it yourself first)
const data = JSON.parse(prompt());
let path = prompt();
while (path !== null) {
const value = path.split(".").reduce((current, key) => current?.[key], data);
console.log(value === undefined ? "(missing)" : JSON.stringify(value));
path = prompt();
}