2016-11-22 69 views
-2

如何獲取json對象的所有後代並對其進行過濾。以下是一個C#代碼,我希望能夠在角度方面做到這一點。它的一部分是Linq。我正在嘗試選擇所有葉子的孩子。如何獲取Json對象的後代

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"] 
+0

所以,你要提取無鑰匙插入陣列的所有冠軍? – Geeky

+0

所有標題沒有兄弟姐妹。因爲一些標題只是問題。 – asahun

回答

1

檢查這個片段

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);

希望這有助於

+0

謝謝,這對我有用。 – asahun