我有3个不同的对象/节点,如下所示,我正在尝试形成finalObj / node,它是3个节点的union(唯一树列表)。
树视图中是否有方法可以根据文本或ID结合3个对象(节点)?
First node:
[ { text: "TreeRoot", items: [
{ text: "Subgroup1" },
{ text: "Subgroup2" }
]}]
Second Node:
[ { text: "TreeRoot", items: [
{ text: "Subgroup3" }
]}]
Third node:
[{ text: "Subgroup3",
items: [ {
text: "subgroup5",
items: [ {
text: "subgroup6",
items: [ {
text: "subgroup7",
items: [ {
text: "subgroup8"
}]
}] }]
}]}]
Final expected node (after merging):
var finalObj= [ { text: "TreeRoot", items: [
{ text: "Subgroup1" },
{ text: "Subgroup2" },
{ text: "Subgroup3",
items: [ {
text: "subgroup5",
items: [ {
text: "subgroup6",
items: [ {
text: "subgroup7",
items: [ {
text: "subgroup8"
}]
}] }]
}]}]}]
编辑:
以下解决方案不适用于其他类型的节点。
对于EX:
var node1 = [
{ text : "TreeRoot",
id:0,
items: [
{ text: "Subgroup1",id:1 },
{ text: "Subgroup2", id:2}
]
}
];
var node2 = [
{
text : "TreeRoot",
id:0,
items: [
{ text: "Subgroup3" ,
id:3}
]
}
];
var node3 = [
{
text : "TreeRoot",
id:0,
items: [
{
text : "Subgroup2",
id:2,
items: [
{
text : "subgroup6",
id:6,
items: [
{
text : "subgroup7",
id:7,
items: [
{
text: "subgroup8",
id:8
}
]
}
]
}
]
}
]
}
];
对于上面的例子,我最初应该只看到树根。扩展时我应该只看到subgroup1,2,3 ......当subgroup2扩展时,我应该能够看到subgroup6,7,8。
我需要唯一的父节点和子节点。如果我使用上面的结构,我得到2个名为Subgroup3的子节点
答案 0 :(得分:2)
虽然你把它标记为Kendo-UI但它实际上是一个编程问题,因为没有用于解决的KendoUI接口(我知道你想用它来合并treeview
节点)它但是使用递归来解决它并不是很难。
这基本上就是你的三个节点:
var node1 = [
{ text : "TreeRoot",
items: [
{ text: "Subgroup1" },
{ text: "Subgroup2" }
]
}
];
var node2 = [
{
text : "TreeRoot",
items: [
{ text: "Subgroup3" }
]
}
];
var node3 = [
{
text : "Subgroup3",
items: [
{
text : "subgroup5",
items: [
{
text : "subgroup6",
items: [
{
text : "subgroup7",
items: [
{
text: "subgroup8"
}
]
}
]
}
]
}
]
}
];
您可以使用以下功能合并它:
function merge(node1, node2) {
if (node2 !== null) {
if (node1.text === node2.text) {
node1.items = node1.items || [];
$.each(node2.items, function (idx2, elem2) {
var found = false;
// Check that elem does not exist on node1
$.each(node1.items, function (idx1, elem1) {
if (!found && elem1.text === elem2.text) {
found = true;
merge(elem1, elem2);
}
});
if (!found) {
node1.items.push(elem2);
}
});
} else {
if (node1.items) {
$.each(node1.items, function (idx, item) {
merge(item, node2);
});
}
}
}
}
它合并了第一个节点中的两个节点。
你应该像这样调用它:
merge(node1[0], node2[0]);
merge(node1[0], node3[0]);
适用于您的方案。
注意:我假设您在每个节点上只有一个元素(即node0
,node1
和node2
是数组,但它们是只有一个元素)
看到它正在运行here