let msg = [
{ payload: { errors: { unknown_language: 'hello' } } },
{ payload: { errors: { number: 1 } } },
{ randomstuff: 42 }
];
// "hello"
extractWithPattern(msg, '[].payload.errors.unknown_language');
// 42
extractWithPattern(msg, '[].randomstuff');
Last active
November 6, 2018 14:39
-
-
Save kopiro/d6643f4b043a9b3ea8a5034bc01e6cf7 to your computer and use it in GitHub Desktop.
Extract from a JS object with a specific pattern
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
function extractWithPattern(input, pattern) { | |
if (input == null) return null; | |
if (pattern == '') return input; | |
const p = pattern.split('.'); | |
let _p = p.shift(); | |
// Array search | |
if (_p === '[]') { | |
_p = p.shift(); | |
for (let _input of input) { | |
if (_input[_p] != null) { | |
const found = extractWithPattern(_input[_p], p.join('.')); | |
if (found) return found; | |
} | |
} | |
return null; | |
} | |
if (p.length === 0) { | |
return input[_p]; | |
} | |
return extractWithPattern(input[_p], p.join('.')); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment