Skip to content

Instantly share code, notes, and snippets.

@matzeeable
Last active November 18, 2022 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matzeeable/875c051d9c7782e75a60a76175108b1d to your computer and use it in GitHub Desktop.
Save matzeeable/875c051d9c7782e75a60a76175108b1d to your computer and use it in GitHub Desktop.
Find object path within nested object with a given key
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