Skip to content

Instantly share code, notes, and snippets.

@andrew-serrano
Created April 30, 2020 20:35
Show Gist options
  • Save andrew-serrano/dc06612e7210573f843ccb6a80f2183c to your computer and use it in GitHub Desktop.
Save andrew-serrano/dc06612e7210573f843ccb6a80f2183c to your computer and use it in GitHub Desktop.
Recursively search an Object and return all matches
// File is a POF of how to recursively search an object
class User {
constructor() {
this.username = "john_doe";
this.password = "password";
}
/**
* Deep search any object like types and return
* one or more values for the property name
* @param {String} keyToFind
* @param {Object} user_settings
* @param {Array} values
* @return {* || Array[*,]}
*/
getField(keyToFind, user_settings, values = new Array()) {
// Return the user settings or the child
// of the user settings
var entries = user_settings === undefined ? Object.entries(this) : Object.entries(user_settings);
// Iterate over the entries array
for (const [key, field] of entries) {
// Return the value if the key is found
if (key === keyToFind) {
values.push(field);
}
// Key was not found and only continue recursively if the value of the
// key is an object like type
if (field.constructor === Object || (typeof field === "object" && field !== null)) {
// Continue down the tree
this.getField(keyToFind, field, values);
}
}
// Return a single value or array of multiple values
return values.length === 1 ? values[0] : values;
}
/**
* Deep search any object like types and set
* a value to that property
* @param {String} keyToFind
* @param {*} value
* @param {Object} user_settings
* @return {Boolean}
*/
setField(keyToFind, value, user_settings) {
// Return the user settings or the child
// of the user settings
var entries = user_settings === undefined ? this : user_settings;
// Iterate over the entries array
for (const entry in entries) {
let field = entries[entry];
// Return the value if the key is found
if (entries.hasOwnProperty(keyToFind)) {
entries[keyToFind] = value;
return true;
}
// Key was not found and only continue recursively if the value of the
// key is an object like type
if (field.constructor === Object || (typeof field === "object" && field !== null)) {
// Continue down the tree
this.setField(keyToFind, value, field);
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment