Javascript Object Search And Get All Possible Nodes
I have a multidimensional object. I need to search a string in each node and need to return an array of nodes contains the string. e.g. Object { 'data': { 'countries': '['abc
Solution 1:
You could try and solve this with recursive function calls
functionparse(string, key, before) {
return before+key+":"+string;
}
functionfindString(string, json, before) {
var results = [];
for (var key in json) {
if (typeof(json[key]) === "string") { // it is a stringif (json[key].contains(string)) { // it contains what it needs to
results.push(parse(string, key, before));
}
} else { // it is an objectArray.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" ]
Solution 2:
var data = {
"countries": "['abc','pqr','xyz']",
"movies": {
"actor": "['abc','pqr','xyz']",
"movie": "['abc','pqr','x toyz']"
}
}
var listAll = function(obj, match, parent){
for( var key in obj ){
if( typeof obj[key] === "string" ){
for( var word of obj[key].split("'") ){
if( word.indexOf(match) !== -1){
if( !parent ){
console.log( key + ':' + word );
}
else{ console.log( parent+":"+key + ':' + word ); }
}
}
}else{
listAll(obj[key], match, (parent||'') + key);
}
}
}
listAll(data,'pq');
> countries:pqr
> movies:actor:pqr
> movies:movie:pqr
Now it should include the full parent list
Post a Comment for "Javascript Object Search And Get All Possible Nodes"