Skip to content

Instantly share code, notes, and snippets.

@knoajp
Last active Feb 2, 2020
Embed
What would you like to do?
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