Skip to content

Instantly share code, notes, and snippets.

@kopiro
Last active November 6, 2018 14:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kopiro/d6643f4b043a9b3ea8a5034bc01e6cf7 to your computer and use it in GitHub Desktop.
Save kopiro/d6643f4b043a9b3ea8a5034bc01e6cf7 to your computer and use it in GitHub Desktop.
Extract from a JS object with a specific pattern

extractWithPattern

Extract from a JS object with a specific pattern

let msg = [
	{ payload: { errors: { unknown_language: 'hello' } } },
	{ payload: { errors: { number: 1 } } },
	{ randomstuff: 42 }
];

// "hello"
extractWithPattern(msg, '[].payload.errors.unknown_language');

// 42
extractWithPattern(msg, '[].randomstuff');
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