2017-03-25 14 views
-2

オブジェクトを解析してツリー構造のように印刷したい。私は処理(privateJetとShip)に問題があります。私は再帰関数でそれをやりたい文字列でオブジェクトを解析してツリー構造で表示する

オブジェクト:

[{"land":[{"vehicles":["car","bus","train"]}]},{"air":[{"commercial":[{"flight":["local","international"]},"privateJet"]},"ship"]}] 

私が得たもの:

enter image description here

コード:

<!doctype html> 
<html> 
<body> 
<div id="abc"></div> 

<script> 
var treeObj = [{"land":[{"vehicles":["car","bus","train"]}]},{"air":[{"commercial":[{"flight":["local","international"]},"privateJet"]},"ship"]}] 

function createTree(obj, parent) { 
    for(key in obj) { 
     if(typeof obj[key] == 'string') { 
      document.getElementById('abc').innerHTML += '<div style="padding-left:10em">' + obj[key] + '</div>'; 
     } else { 
      console.log(key, obj); 
      x = 1; 
      for(categoryKey in obj[key]) { 

       var category = obj[key]; 
       if(Object.prototype.toString.call(category[categoryKey]) === '[object Array]') { 
        document.getElementById('abc').innerHTML += '<div style="padding-left:'+ (parent * 5) +'em">' + categoryKey; 
        createTree(category[categoryKey], x); 
        document.getElementById('abc').innerHTML += '</div>'; 
       } 
       x++; 
      } 
     } 
    } 
} 

createTree(treeObj, 0); 

</script> 
</body> 
</html> 
+0

...あなたはあなたのコードを追加するのを忘れ。 – trincot

+1

^^ご質問... –

答えて

1

適切なオブジェクトを使用すると、新しい順序付けられていないリストとリストアイテムを構築できます。

var data = [{ land: [{ vehicles: ["car", "bus", "train"] }] }, { air: [{ commercial: [{ flight: ["local", "international"] }, "privateJet"] }] }, { sea: ["ship"] }]; 
 

 
document.body.appendChild(data.reduce(function getValues(ul, el) { 
 
    var li = document.createElement('li'), 
 
     key; 
 

 
    if (typeof el === 'object') { 
 
     key = Object.keys(el)[0]; 
 
     li.appendChild(document.createTextNode(key)); 
 
     if (Array.isArray(el[key])) { 
 
      li.appendChild(el[key].reduce(getValues, document.createElement('ul'))); 
 
     } 
 
    } else { 
 
     li.appendChild(document.createTextNode(el)); 
 
    } 
 
    ul.appendChild(li); 
 
    return ul; 
 
}, document.createElement('ul')));

関連する問題