2016-11-22 16 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

関連する問題