Skip to content

Instantly share code, notes, and snippets.

@lukeribchester
Created April 24, 2022 03:38
Show Gist options
  • Save lukeribchester/f8da6bda42429b66fbfdd11ebcf16d96 to your computer and use it in GitHub Desktop.
Save lukeribchester/f8da6bda42429b66fbfdd11ebcf16d96 to your computer and use it in GitHub Desktop.
function isObject(object) {
return object != null && object.constructor.name === 'Object';
}
function isArray(object) {
return object != null && object.constructor.name === 'Array';
}
/**
* Find all values corresponding to a matching property.
*
* @param property
* @param object
* @param values
* @returns {*[]}
*/
function findAllValuesOfMatchingProperty(property, object, values = []) {
if (isArray(object)) {
object.forEach(value => {
return findAllValuesOfMatchingProperty(property, value, values);
});
}
if (isObject(object)) {
Object.entries(object).forEach(([key, value]) => {
if (key.match(property)) values.push(value);
return findAllValuesOfMatchingProperty(property, value, values);
});
}
return values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment