Last active
November 18, 2022 22:34
-
-
Save matzeeable/875c051d9c7782e75a60a76175108b1d to your computer and use it in GitHub Desktop.
Find object path within nested object with a given key
This file contains 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
function findObjectWithKey(object, key, multiple = false, _recursiveData) { | |
var value, path = _recursiveData?.path || []; | |
Object.keys(object).some(function(k) { | |
if (k === key) { | |
value = object; | |
path.push("|"); | |
if (!multiple) { | |
return true; | |
} | |
} else if (typeof object?.[k] === 'object') { | |
value = findObjectWithKey(object[k], key, multiple, { path }); | |
if (value !== undefined) { | |
path.push(k); | |
if (!multiple) { | |
return true; | |
} | |
} | |
} | |
}); | |
return _recursiveData | |
? value | |
: value ? path.join(".").split("|").filter(Boolean).map((i) => `${i.split(".").filter(Boolean).reverse().join(".")}.${key}`) : false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment