Last active
June 16, 2020 10:16
-
-
Save FeMaffezzolli/85587fa39d7e10d82a03e4153200d0e8 to your computer and use it in GitHub Desktop.
Search value in object by concatened string of keys of nested objects.
This file contains hidden or 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
/** | |
* 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