Skip to content

Instantly share code, notes, and snippets.

@tq-bit
Created July 16, 2025 08:36
Show Gist options
  • Save tq-bit/d84b787c9152b99ecc0b60f2023475b8 to your computer and use it in GitHub Desktop.
Save tq-bit/d84b787c9152b99ecc0b60f2023475b8 to your computer and use it in GitHub Desktop.
Query JSON
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