Find a String inside a JSON object with recursivity in Node.JS
Simple thing:
const THE_UNKNOWN = {
a: 2,
b: "hello",
c: {
d: 34.21,
e: "TARGET",
f: {
g: "not easter egg",
h: {
i: "TARGET"
}
},
j: [
{
k: 308
},
{
l: "TARGET"
}
],
m: [
"some",
"string",
"array",
"TARGET"
]
}
};
function find(what, here) {
Object.keys(here).forEach(property => {
if (typeof here[property] === "string") {
if (here[property] === what) {
console.log("%s found inside %s", what, property.toString());
}
} else if (typeof here[property] === "object") {
find(what, here[property]);
}
});
}
find("TARGET", THE_UNKNOWN);
Your output should be this:
TARGET found inside e
TARGET found inside i
TARGET found inside l
TARGET found inside 3