Created
December 12, 2018 05:49
-
-
Save antonmedv/065462763d750c9db93154dce996eaa1 to your computer and use it in GitHub Desktop.
Search Snippet
This file contains 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
global.find = re => json => [...find(json, re)] | |
function* find(v, regex, path = '') { | |
if (regex.test(path)) { | |
yield path | |
return | |
} | |
if (typeof v === 'undefined' || v === null) { | |
return | |
} | |
if (Array.isArray(v)) { | |
let i = 0 | |
for (let value of v) { | |
const prefix = (path === '' ? 'this' : path) | |
yield* find(value, regex, prefix + '[' + i++ + ']') | |
} | |
return | |
} | |
if (typeof v === 'object' && v.constructor === Object) { | |
const entries = Object.entries(v) | |
for (let [key, value] of entries) { | |
yield* find(value, regex, path + '.' + key) | |
} | |
return | |
} | |
if (regex.test(v)) { | |
yield path | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment