Skip to content

Instantly share code, notes, and snippets.

@jfromaniello
Created March 15, 2018 20:49
Show Gist options
  • Save jfromaniello/a38fefb3e679aa7abf230e8fe16a5dad to your computer and use it in GitHub Desktop.
Save jfromaniello/a38fefb3e679aa7abf230e8fe16a5dad to your computer and use it in GitHub Desktop.
//lets say you want to find the property on the `resp` object
//that contains the url of the request
request.get('http://example.com/foo/bar', (err, resp, body) => {
console.dir(findMatchingProperty(resp, v => typeof v === 'string' && v.match(/\/foo\/bar/)));
});
/**
The result is:
[ '.request.path',
'.request.href',
'.request.uri.path',
'.request.uri.href',
'.request.uri.pathname',
'.socket._httpMessage.path',
'.socket._httpMessage._header' ]
*/
/**
* This functions allows you to find a property in a graph
* of objects matching a condition.
*
* This is specially useful when you have a complex object
* and you know it has a property with a value but you don't
* know the exact name of the property.
*
* @param input the starting point
* @param func the function to match the condition
* @param analyzed ignore this parameter, it is used only to avoid walking in circles.
*/
function findMatchingProperty(input, func, analyzed) {
analyzed = analyzed || [];
const results = [];
if (typeof input === 'undefined') { return results; }
if (analyzed.indexOf(input) > -1) { return results; }
analyzed.push(input);
if (Array.isArray(input)) {
input.forEach((val, index) => {
if (func(val)) {
results.push(`[${index}]`);
} else {
findMatchingProperty(val, func, analyzed).forEach(m => results.push(`[${index}]${m}`))
}
});
} else if (typeof input === 'object') {
for(var name in input) {
var val = input[name];
if (func(val)) {
results.push(`.${name}`);
} else {
findMatchingProperty(val, func, analyzed).forEach(m => results.push(`.${name}${m}`));
}
}
}
results.sort((a, b) => a.length - b.length);
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment