Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@knoajp
Last active February 2, 2020 02:59
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 knoajp/82039fa5ab96fe4b1a60aab22c0fc0b1 to your computer and use it in GitHub Desktop.
Save knoajp/82039fa5ab96fe4b1a60aab22c0fc0b1 to your computer and use it in GitHub Desktop.
find key or value from an object recursively
(function(){
const target = window;
const search = /search/;
const type = {
key: true,
value: true,
};
const scan = function(t, path = '', chain = [t]){
//console.log(path);
switch(true){
case(isWindow(t)):
case(isObject(t)):
if(type.key === true) Object.keys(t).forEach(key => {
if(search.test(key)) console.log('Found key:', path + '.' + key, t[key]);
});
Object.keys(t).filter(key => chain.every(c => c !== t[key])).forEach(key => scan(t[key], path + '.' + key, [...chain, t[key]]));
break;
case(isArray(t)):
t.filter(v => chain.every(c => c !== v)).forEach((v, i) => scan(v, path + '[' + i + ']', [...chain, v]));
break;
case(isFunction(t)):
if(type.value === true){
if(search.test(t.name)) console.log('Found value:', path, t);
}
break;
case(isString(t)):
case(isNumber(t)):
if(type.value === true){
if(search.test(t)) console.log('Found value:', path, t);
}
break;
default:
break;
}
};
/* isObject by https://chaika.hatenablog.com/entry/2019/08/16/083000 */
const isWindow = (x) => (x === window);
const isObject = (x) => (x !== null) && (typeof x === 'object') && (x.constructor === Object);
const isArray = (x) => Array.isArray(x);
const isFunction = (x) => (typeof x === 'function');
const isString = (x) => (typeof x === 'string');
const isNumber = (x) => (typeof x === 'number');
scan(target);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment