Created
January 24, 2023 09:10
-
-
Save p0rsche/8f86117861817c77ed8acf1f145f95e9 to your computer and use it in GitHub Desktop.
Get object values by string sequence
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
// 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