Skip to content

Instantly share code, notes, and snippets.

@zorgick
Created April 18, 2019 15:50
Show Gist options
  • Save zorgick/e63821f2175205b724177c75e1339778 to your computer and use it in GitHub Desktop.
Save zorgick/e63821f2175205b724177c75e1339778 to your computer and use it in GitHub Desktop.
/**
*
* @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