gpt4 book ai didi

javascript - 从数据中为 jqtree 构建树 json

转载 作者:行者123 更新时间:2023-11-30 16:47:31 28 4
gpt4 key购买 nike

我正在尝试为以下构建 jqtree 的数据创建树 json

var data = [
{
"director": "Name1",
"name": "sub-sub-child1",
"teamname": "sub-child1",
"teamManager": "child1"
},

{
"director": "Name1",
"name": "sub-sub-child2",
"teamname": "sub-child1",
"teamManager": "child1"
},
{
"director": "Name1",
"name": "sub-sub-child2",
"teamname": "sub-child2",
"teamManager": "child2"
},
{
"director": "Name2",
"name": "sub-sub-child1",
"teamname": "sub-child1",
"teamManager": "child1"
},
{
"director": "Name2",
"name": "sub-sub-child2",
"teamname": "sub-child2",
"teamManager": "child2"
},
{
"director": "Name3",
"name": "sub-sub-child1",
"teamname": "sub-child1",
"teamManager": "child1"
},
{
"director": "Name3",
"name": "sub-sub-child2",
"teamname": "sub-child2",
"teamManager": "child2"
}
];

console.log(data);

var aNode = [];
var aTempNode = [];
$.each(data, function(index, value) {
//console.log(value);
var key = {};
if($.inArray(value.director, aTempNode) == -1) {
aTempNode.push(value.director);
key['label'] = value.director;
key['children'] = [{label: value.teamManager, children: [{label: value.teamname, children: [{label: value.name}]}]}];
aNode.push(key);
} else {
//console.log(aNode)
if(key['teamname'] == aNode.children) {

}
}

});
console.log(aNode);

fiddle

EDIT2

树应该是这种形式

Name1
|
|___child1
| |
| |___sub-child1
| | |
| | |___sub-sub-child1
| | |___sub-sub-child2
| |
| |___sub-child2
| |
| |___sub-sub-child1
| |___sub-sub-child2
|
|____child2

编辑1

我已经完成一半了。我很困惑如何从这里开始。 fiddle

最佳答案

试试这个,你会在“temp”变量中得到你需要的东西

var temp = [];
$.each(data, function(row, val) {
var director = $.grep(temp, function(v) {
return v.label == val.director
});

if (director.length) {
var teamManager = $.grep(director[0].children, function(v) {
return v.label == val.teamManager
})
if (teamManager.length) {
var teamname = $.grep(teamManager[0].children, function(v) {
return v.label == val.teamname
})
if (teamname.length) {
var name = $.grep(teamname[0].children, function(v) {
return v.label == val.name
})
if (!name.length) {
teamname[0].children.push({
label: val.name,
children: []
});
}
} else {
teamManager[0].children.push({
label: val.teamname,
children: [{
label: val.name,
children: []
}]
});
}

} else {
director[0].children.push({
label: val.teamManager,
children: [{
label: val.teamname,
children: [{
label: val.name,
children: []
}]
}]
})
}
} else {
temp.push({
label: val.director,
children: [{
label: val.teamManager,
children: [{
label: val.teamname,
children: [{
label: val.name,
children: []
}]
}]
}]
});
}

});

关于javascript - 从数据中为 jqtree 构建树 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31016667/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com