JavaScript object search and get all possible nodes -
i have multidimensional object. need search string in each node , need return array of nodes contains string.
e.g.
object
{ "data": { "countries": "['abc','pqr','xyz']", "movies": { "actor": "['abc','pqr','xyz']", "movie": "['abc','pqr','x toyz']" } }
and if want search 'pq' need array
countries:pqr movies:actor:pqr countries:movie:pqr
as result.
you try , solve recursive function calls
function parse(string, key, before) { return before+key+":"+string; } function findstring(string, json, before) { var results = []; (var key in json) { if (typeof(json[key]) === "string") { // string if (json[key].contains(string)) { // contains needs results.push(parse(string, key, before)); } } else { // 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!" // not added } } } }; console.log(findstring("pqr", json.data, ""));
this outputs array like:
array [ "countries:pqr", "movies:actor:pqr", "movies:movie:pqr", "oranges:potatoes:pqr", "oranges:zebras:lions:pqr" ]
Comments
Post a Comment