Created
April 18, 2019 15:50
-
-
Save zorgick/e63821f2175205b724177c75e1339778 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
/** | |
* | |
* @param {Object} obj source object to be traversed | |
* @param {RegExp} fieldName regular expression that represents a required property | |
*/ | |
export const getFieldValues = (obj, fieldName) => { | |
if (Object.keys(obj).length === 0) { | |
return | |
} | |
const keys = Object.keys(obj) | |
const values = keys.reduce((acc, key) => { | |
// no need in non-iterable properties | |
if (!obj.hasOwnProperty(key)) { | |
return acc | |
} | |
// the property the script is looking for | |
if (fieldName.test(key)) { | |
return typeof obj[key] === 'string' ? [...acc, obj[key]] : [...acc, ...obj[key]] | |
} | |
const currentValue = obj[key] | |
if (typeof currentValue === 'number' || typeof currentValue === 'string') { | |
return acc | |
} | |
// do this block only for objects | |
if (!Array.isArray(currentValue)) { | |
const nextLevelValues = getFieldValues(currentValue, fieldName) | |
console.log('nextLevelValues: ', nextLevelValues) | |
return nextLevelValues && nextLevelValues.length > 0 ? [...acc, ...nextLevelValues] : acc | |
} | |
return acc | |
}, []) | |
return values | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment