Skip to content

Instantly share code, notes, and snippets.

@RienNeVaPlus
Created September 20, 2022 02:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RienNeVaPlus/a57e989e464f1c24d9bcaf2458773d3f to your computer and use it in GitHub Desktop.
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`
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
}
@RienNeVaPlus
Copy link
Author

Example:

const obj = {a: [ {b: true} ]}
const value = querySelector(obj, 'a[0].b') // true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment