JSFiddle - React, Tailwind, and code Playground
HTML
<h2>
Result
</h2>
<div id="result1"></div>
<br />
<div id="result2"></div>
<br />
<div id="result3"></div>
JavaScript
/* interface FindKeysArguments {
obj: { [key: string]: any };
key: string;
pathToKey?: string;
} */
function findPathsToKey(options) {
const results = [];
(function findKey({
key,
obj,
pathToKey,
}) {
const oldPath = `${pathToKey ? pathToKey + "." : ""}`;
if (obj.hasOwnProperty(key)) {
results.push(`${oldPath}${key}`);
}
if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
for (const k in obj) {
if (obj.hasOwnProperty(k)) {
if (Array.isArray(obj[k])) {
for (let j = 0; j < obj[k].length; j++) {
findKey({
obj: obj[k][j],
key,
pathToKey: `${oldPath}${k}[${j}]`,
});
}
}
if (obj[k] !== null && typeof obj[k] === "object") {
findKey({
obj: obj[k],
key,
pathToKey: `${oldPath}${k}`,
});
}
continue;
}
}
}
})(options);
return results;
}
const myObjWithDupl = {
parentKey: {
someImportantStuff: "134",
arr: [
{a:1, b: 2, c: { d: "D VLAUE"}, yy: "bla" },
{a:1, b: 2, c: { d: "D VLAUE"}, yy: "bla" },
{a:1, b: 2, c: { d: "D VLAUE"}, xxx: "bla" },
],
},
f: "hello",
x: {
y: "y_value",
}
}
const container1 = document.querySelector("#result1");
const container2 = document.querySelector("#result2");
const container3 = document.querySelector("#result3");
container1.innerText = findPathsToKey({ obj: myObjWithDupl, key: "d" }).join("\n")
container2.innerText = findPathsToKey({ obj: myObjWithDupl, key: "x" }).join("\n")
container3.innerText = findPathsToKey({ obj: myObjWithDupl, key: "someImportantStuff" }).join("\n")