Created
April 19, 2019 15:28
-
-
Save simonwep/f8e77fd7c1c7064a931d39414fea2e26 to your computer and use it in GitHub Desktop.
Searches for a value in a object
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
function searchFor(val, s, all = true) { | |
const results = []; | |
const handleValue = (key, value, p) => { | |
const da = typeof key === 'string' && key.match(/^[_a-zA-Z][\w\d_]*$/); | |
const query = p + (da ? `.${key}` : `[${key}]`); | |
if (value === s) { | |
return query; | |
} else if (typeof value === 'object') { | |
search(value, query); | |
} | |
}; | |
function search(val, p = '') { | |
if (typeof val === 'object') { | |
for (const [key, value] of Object.entries(val)) { | |
const res = handleValue(key, value, p); | |
if (res) { | |
results.push(res.substr(1)); | |
if (all) { | |
return; | |
} | |
} | |
} | |
} else if (s === val) { | |
return p + s; | |
} | |
return null; | |
} | |
search(val); | |
if (all) { | |
return results; | |
} else { | |
return results[0] || null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment