Skip to content

Instantly share code, notes, and snippets.

@morulus
Last active November 28, 2019 12:17
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 morulus/a5e3614682276f85e625f6f333e12c02 to your computer and use it in GitHub Desktop.
Save morulus/a5e3614682276f85e625f6f333e12c02 to your computer and use it in GitHub Desktop.
Find all property names xpath in the nested javascript structure
export default function findProperty(obj, name, xpath = ["[root]"], storedObjects = []) {
let foundedKeys = [];
if (storedObjects.includes(obj)) {
return foundedKeys;
}
storedObjects.push(obj);
if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
foundedKeys = foundedKeys.concat(
findProperty(obj[i], name, xpath.concat([i]), storedObjects)
);
}
} else if (obj && typeof obj === "object") {
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === name) {
foundedKeys.push(xpath.join(".") + "." + key);
}
if (typeof obj[key] === "object") {
foundedKeys = foundedKeys.concat(
findProperty(obj[key], name, xpath.concat([key]), storedObjects)
);
}
}
}
return foundedKeys;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment