Skip to content

Instantly share code, notes, and snippets.

@THEtheChad
Created January 8, 2018 09:26
Show Gist options
  • Save THEtheChad/5dcc25242b226758ea8aeb702e78e269 to your computer and use it in GitHub Desktop.
Save THEtheChad/5dcc25242b226758ea8aeb702e78e269 to your computer and use it in GitHub Desktop.
function locate(target, value, path = null){
if(target instanceof RegExp){
if(target.test(value)) return path
}
else{
if(value === target) return path
}
if(Array.isArray(value)){
return value.reduce((memo, v, i) =>
memo || locate(target, v, path ? `${path}[${i}]` : `[${i}]`), null)
}
if(value === Object(value)){
return Object.keys(value).reduce((memo, k) =>
memo || locate(target, value[k], path ? `${/]$/.test(path) ? path : path + '.'}${k}` : k), null)
}
return null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment