Skip to content

Instantly share code, notes, and snippets.

@brandonbarringer
Last active November 14, 2022 18:21
Show Gist options
  • Save brandonbarringer/d244eeb0fd5139d0a18df76c79fab446 to your computer and use it in GitHub Desktop.
Save brandonbarringer/d244eeb0fd5139d0a18df76c79fab446 to your computer and use it in GitHub Desktop.
Get the value of an object using dot notation in a string
/*
const person = {
name: 'John',
age: 30,
address: {
street: 'Main Street',
city: 'New York',
state: 'NY',
zip: '10001'
},
occupation: {
title: 'Developer',
company: 'Google',
type: {
name: 'Full Time',
hours: 40
}
}
}
getObjectValueFromString(person, 'occupation.type.hours') // 40
*/
const getObjectValueFromString = (object, string) => {
return string.split('.').reduce((o, i) => o[i], object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment