Created
July 16, 2025 08:36
-
-
Save tq-bit/d84b787c9152b99ecc0b60f2023475b8 to your computer and use it in GitHub Desktop.
Query JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const nestedUserData = { | |
user: { | |
name: 'John Doe', | |
age: 30, | |
address: { | |
street: '123 Main St', | |
city: 'Anytown', | |
state: 'CA', | |
zip: '12345' | |
} | |
} | |
}; | |
function getNestedValues(object, paths) { | |
return paths.map(path => getNestedValue(object, path)); | |
} | |
function getNestedValue(object, path) { | |
return path.split('.').reduce((acc, key) => (acc && acc[key]) || undefined, object); | |
} | |
const [street, city] = getNestedValues(nestedUserData, ['user.address.street', 'user.address.city']); | |
const notDefined = getNestedValue(nestedUserData, 'user.test.post'); | |
console.log(street); // Output: 123 Main St | |
console.log(city); // Output: Anytown | |
console.log(notDefined); // Output: undefined |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment