Skip to content

Instantly share code, notes, and snippets.

@p0rsche
Created January 24, 2023 09:10
Show Gist options
  • Save p0rsche/8f86117861817c77ed8acf1f145f95e9 to your computer and use it in GitHub Desktop.
Save p0rsche/8f86117861817c77ed8acf1f145f95e9 to your computer and use it in GitHub Desktop.
Get object values by string sequence
// using string sequence, get object key
//'red.big.apple', {red: { big: { apple: 'apple'}}} => 'apple'
// 'red.fast.fancy.car', { red: { slow: 'something'}} => undefined
const get = (keySequence, nestedObject) => {
const seqArr = keySequence.split(".");
let result = nestedObject;
while (seqArr.length > 0) {
let key = seqArr.shift(); // seqArr now has length-1
if (typeof result[key] !== "undefined") {
result = result[key];
} else {
return;
}
}
return result;
};
console.log(get("red.big.apple", { red: { big: { apple: "apple" } } }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment