我的数组结果来自ajax:
[
{id: 1, title: 'hello', parent: 0, children: [
{id: 3, title: 'hello', parent: 1, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 0, children: [
{id: 8, title: 'hello', parent: 2}
]}
]
我需要在选择列表中获取此列表,现在我有了这段代码:
$.ajax({
type: "POST",
url: '../ajax/get_parent',
data: ({ cat: all }),
dataType: "json",
success: function(data) {
var sel = document.getElementById('parentvalue');
var opt = document.createElement('option');
opt.innerHTML = "Select";
opt.value = "";
sel.appendChild(opt);
for (var i = 0; i < data.length; i++) {
if (data[i]['title']) {
var opt = document.createElement('option');
opt.innerHTML = data[i]['title'];
opt.value = data[i]['id'];
sel.appendChild(opt);
}
}
}
});
我只得到一个级别的数组,我需要所有的潜艇,
我该如何解决这个问题?
我需要
- hello
-- hello
--- hello
--- hello
--- hello
- hello
-- hello
谢谢
答案 0 :(得分:0)
您可以递归地解析数组以检查所有子元素......
var data = [
{id: 1, title: 'hello1', parent: 0, children: [
{id: 3, title: 'hello2', parent: 1, children: [
{id: 4, title: 'hello3', parent: 3, children: [
{id: 5, title: 'hello4', parent: 4},
{id: 6, title: 'hello5', parent: 4}
]},
{id: 7, title: 'hello6', parent: 3}
]}
]},
{id: 2, title: 'hello7', parent: 0, children: [
{id: 8, title: 'hello8', parent: 2}
]}
]
function getKeys(data){
var arr = [];
for(var i=0; i<data.length; i++){
arr.push({title: data[i].title, id: data[i].id});
if(data[i].hasOwnProperty("children")){
var nestedArr = getKeys(data[i].children);
if(nestedArr){
arr = arr.concat(nestedArr);
}
}
}
return arr;
}
var _d = getKeys(data);
console.log(_d);
// Use _d to generate the select dropdown now
答案 1 :(得分:0)
我认为列表的父母价值存在一些不匹配。
您可以使用递归函数实现此目的。请尝试以下方式:
var list = [
{id: 1, title: 'hello', parent: 1, children: [
{id: 3, title: 'hello', parent: 2, children: [
{id: 4, title: 'hello', parent: 3, children: [
{id: 5, title: 'hello', parent: 4},
{id: 6, title: 'hello', parent: 4}
]},
{id: 7, title: 'hello', parent: 3}
]}
]},
{id: 2, title: 'hello', parent: 1, children: [
{id: 8, title: 'hello', parent: 2}
]}
]
var html = '';
function createLI(list){
html += '<ul>';
list.forEach(function(item){
html += '<li>' + item.parent + ': ' + item.title + '</li>';
if(item.children){
createLI(item.children);
}
html += '</li>';
})
html += '</ul>';
}
createLI(list);
document.body.innerHTML = html;
&#13;