2016-11-22 2 views
-2

Wie bekomme ich alle Nachkommen eines JSON-Objekts und filter es. das folgende ist ein C# code und ich möchte es in der eckigen seite tun können. Ein Teil davon ist ein Linq. Ich versuche alle Blattkinder auszuwählen.So erhalten Sie Nachkommen von Json-Objekt

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

So möchten Sie alle Titel ohne Schlüssel in Array extrahieren? – Geeky

+0

alle Titel ohne Geschwister. weil einige der Titel nur Fragen sind. – asahun

Antwort

1

prüfen diese Schnipsel

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

hoffe, das hilft

+0

Danke, das hat für mich funktioniert. – asahun

Verwandte Themen