Fisseha Fisseha - 13 days ago 7
AngularJS Question

How to get descendants of Json object

How do I get all descendants of of a json object and filter it. the following is a c# code and I want to be able do it in angular side. Some part of it is a Linq. I am trying to select all leaf children.

e.g. if the following is the input, the answer could be at any level deep.

{
"title": "first question?",
"yes": {"title": "answer A" },
"no": {
"title": "second question?",
"yes": {
"title": "thirsd question?",
"yes": {
"title": "Fifth question?",
"yes": {
"title": "fourth question",
"yes": {"title": "answer D"},
"no": {
"title": "another question?",
"yes": { "title": "answer E" },
"no": {"title": "answer F"}
}
},
"no": {"title": "answer B"}
},
"no": {"title": "Answer F"}
},
"no": {"title": "Answer G"}
}
}

The output would be:

["answer A", "answer B", "answer D", "Answer F", "Answer G", "answer E"]

Answer

Check this snippet

var obj={
 "title": "first question?",
   "yes": {"title": "answer A" },
   "no": {
     "title": "second question?",
     "yes": {
       "title": "thirsd question?",
       "yes": {
         "title": "Fifth question?",
         "yes": {
           "title": "fourth question",
           "yes": {"title": "answer D"},
           "no": {
             "title": "another question?",
             "yes": { "title": "answer E" },
             "no": {"title": "answer F"}
           }
         },
         "no": {"title": "answer B"}
       },
       "no": {"title": "Answer F"}
     },
     "no": {"title": "Answer G"}
    }
}
var titles=[];
getTitle(obj);
function getTitle(obj){
  var keyLen=Object.keys(obj).length;

  Object.keys(obj).forEach(function(key){
       if(keyLen==1 && key=="title")
           titles.push(obj[key]);
        else if(obj[key] instanceof Object)
          getTitle(obj[key]);
  });

}

console.log(titles);

Hope this helps

Comments