Last active
November 14, 2022 18:21
-
-
Save brandonbarringer/d244eeb0fd5139d0a18df76c79fab446 to your computer and use it in GitHub Desktop.
Get the value of an object using dot notation in a string
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 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