Medium
Access a Nested Property in an Object
Description
In JavaScript, objects can contain other objects as properties, creating a nested structure.
For example, an object might store a person's details, including their address, which is itself an object.
In this challenge, you will write a function named getNestedProperty that takes an object and a string representing the path to a nested property (e.g., "address.city") and returns the value of that nested property.
If the property does not exist, the function should return "404".
Example Usage:
const person = {name: "Alice",address: {city: "New York",zipCode: "10001"}};console.log(getNestedProperty(person, "address.city")); // Expected output: "New York"console.log(getNestedProperty(person, "address.country")); // Expected output: "404"console.log(getNestedProperty(person, "name")); // Expected output: "Alice"
Constraints:
- The input will always be a valid object and a string representing the path to a nested property.
- The function should return the value of the nested property if it exists, or "404" if it does not.
Did you know?
www stands for World Wide Web.
Test Cases
Input:
{ "name": "Alice", "address": { "city": "New York", "zipCode": "10001" } }
Expected Output:
"New York"
Premium Question
This question is only available to premium users.
Looking to level up your coding skills? Upgrade to Premium to access premium questions, personalized learning paths, reports, and more!