-
-
Save phellipeandrade/8d59f4b3b5a6e16a30695df2a4622ec3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment