function populateUL($ul, data) {
// Register the given UL element as the root in a new data structure
var hash = {
"": { $ul: $ul }
};
// Key the objects by their id, and create individual LI elements for them,
// and an empty UL container for their potential child elements
data.forEach(function (o) {
var $ul = $("<ul>");
hash[o.id] = {
$ul: $ul,
$li: $("<li>").text(o.name).append($ul)
};
});
// Append each LI element to the correct parent UL element
data.forEach(function (o) {
hash[o.parentDirId].$ul.append(hash[o.id].$li);
});
}
// Sample response object
var response = [{
"id":"70b77ddd-6c15",
"path":"/test",
"name":"test",
"parentDirName":"",
"parentDirId":""
}, {
"id":"076ac97d",
"path":"/test/chess",
"name":"chess",
"parentDirName":"test",
"parentDirId":"70b77ddd-6c15"
}, {
"id":"076ac97e",
"path":"/test/bingo",
"name":"bingo",
"parentDirName":"test",
"parentDirId":"70b77ddd-6c15"
}, {
"id":"076ac97f",
"path":"/test/chess/major pieces",
"name":"major pieces",
"parentDirName":"chess",
"parentDirId":"076ac97d"
}, {
"id":"076ac97g",
"path":"/test/chess/major pieces/rook",
"name":"rook",
"parentDirName":"major pieces",
"parentDirId":"076ac97f"
}, {
"id":"076ac97h",
"path":"/test/chess/major pieces/queen",
"name":"queen",
"parentDirName":"major pieces",
"parentDirId":"076ac97f"
}, {
"id":"076b0000",
"path":"/test/chess/minor pieces",
"name":"minor pieces",
"parentDirName":"chess",
"parentDirId":"076ac97d"
}, {
"id":"076b0001",
"path":"/test/chess/minor pieces/knight",
"name":"knight",
"parentDirName":"minor pieces",
"parentDirId":"076b0000"
}, {
"id":"076b0002",
"path":"/test/chess/minor pieces/bishop",
"name":"bishop",
"parentDirName":"minor pieces",
"parentDirId":"076b0000"
}];
// Inject response data into document
populateUL($("#root"), response);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="root"></ul>
你可以添加示例輸入和輸出? – Tezra