Skip to content

Instantly share code, notes, and snippets.

@fernandocamargo
Created August 30, 2019 15:23
Show Gist options
  • Save fernandocamargo/df8fc55a0e4722c56bb189b3fe312563 to your computer and use it in GitHub Desktop.
Save fernandocamargo/df8fc55a0e4722c56bb189b3fe312563 to your computer and use it in GitHub Desktop.

Revisions

  1. fernandocamargo created this gist Aug 30, 2019.
    40 changes: 40 additions & 0 deletions search.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    const sample = [
    [
    [
    [
    [
    [
    {
    foo: [{ rate: 2.18 }],
    },
    ],
    ],
    ],
    ],
    ],
    {
    fieldCount: 0,
    affectedRows: 0,
    insertId: 0,
    serverStatus: 0,
    message: '',
    protocol141: true,
    changedRows: 0,
    },
    ];

    const search = (object, target, defaultValue) =>
    Object.entries(object).reduce((stack, [key, value]) => {
    switch (true) {
    case key === target:
    return value;
    case !!Object.keys(value).length:
    return search(value, target, stack);
    default:
    return stack;
    }
    }, defaultValue);

    console.log(search(sample, 'rate')); // 2.18
    console.log(search(sample, 'protocol141')); // true
    console.log(search(sample, 'hueBR', 'LOL')); // 'LOL'