Skip to content

Instantly share code, notes, and snippets.

@simonwep
Created April 19, 2019 15:28
Show Gist options
  • Save simonwep/f8e77fd7c1c7064a931d39414fea2e26 to your computer and use it in GitHub Desktop.
Save simonwep/f8e77fd7c1c7064a931d39414fea2e26 to your computer and use it in GitHub Desktop.
Searches for a value in a object
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