You could try and solve this with recursive function calls
function parse(string, key, before) {
return before+key+":"+string;
}
function findString(string, json, before) {
var results = [];
for (var key in json) {
if (typeof(json[key]) === "string") { // it is a string
if (json[key].contains(string)) { // it contains what it needs to
results.push(parse(string, key, before));
}
} else { // it is an object
Array.prototype.push.apply(results, findString(string, json[key], before+key+":"));
}
}
return results;
}
var json = {
data: {
countries: "['abc','pqr','xyz']",
movies: {
actor: "['abc','pqr','xyz']",
movie: "['abc','pqr','x toyz']"
},
oranges: {
potatoes: "['abc','pqr','xyz']",
zebras: {
lions: "['abc','pqr','xyz']",
tigers: "oh my!" // does not get added
}
}
}
};
console.log(findString("pqr", json.data, ""));
This outputs an array like:
Array [ "countries:pqr", "movies:actor:pqr", "movies:movie:pqr", "oranges:potatoes:pqr", "oranges:zebras:lions:pqr" ]
4
solved JavaScript object search and get all possible nodes