Skip to content

Instantly share code, notes, and snippets.

@jfromaniello
Created March 15, 2018 20:49
Show Gist options
  • Select an option

  • Save jfromaniello/a38fefb3e679aa7abf230e8fe16a5dad to your computer and use it in GitHub Desktop.

Select an option

Save jfromaniello/a38fefb3e679aa7abf230e8fe16a5dad to your computer and use it in GitHub Desktop.

Revisions

  1. jfromaniello created this gist Mar 15, 2018.
    19 changes: 19 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    //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' ]
    */
    43 changes: 43 additions & 0 deletions findMatchingProperty.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    /**
    * 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;
    }