Skip to content

Instantly share code, notes, and snippets.

@FeMaffezzolli
Last active June 16, 2020 10:16
Show Gist options
  • Save FeMaffezzolli/85587fa39d7e10d82a03e4153200d0e8 to your computer and use it in GitHub Desktop.
Save FeMaffezzolli/85587fa39d7e10d82a03e4153200d0e8 to your computer and use it in GitHub Desktop.
Search value in object by concatened string of keys of nested objects.
/**
* Search value in object by concatened string of keys of nested objects.
*
* @example
*
* Find street name from object:
*
* const obj = {
* address: {
* district: {
* street: {
* name: 'Gustave Rapin'
* }
* }
* }
* }
*
* Using this search parameter:
*
* "address.district.street.nome"
*
* @param {object} input - Object on which search will occur.
* @param {string} search - Concatenated string of object keys.
* @param {string} divider - Divider used on 'search' concatenation.
* @param {*} [defaultValue=null] - What must be return if not found.
*/
function searchDepthValue(
input,
search,
divider = '.',
defaultValue = null,
) {
const keys = search.split(divider)
let result
let pointer = input
keys.forEach((key) => {
if (pointer[key]) {
result = pointer[key]
pointer = result
} else {
result = defaultValue
}
})
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment