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

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -