Created
September 20, 2022 02:19
-
-
Save RienNeVaPlus/a57e989e464f1c24d9bcaf2458773d3f to your computer and use it in GitHub Desktop.
A querySelector utility to fetch values from an object by providing a path string. `querySelector({a:[{b:3]}, 'a[0].b') === 3`
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 querySelectorRegex = /(?<=\[)(?!")[^\]]+|(?<=\[")[^"]+|[^."[\]]+/g | |
export function objectQuerySelector(obj: any, path: string){ | |
const match = path.match(objectQueryRegex) | |
return match ? match.reduce((res, prop) => res[prop], obj) : undefined | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: