Although you tag it as Kendo-UI it is actually a programming problem since there is no KendoUI interface for solving (I know that you want to use it for merging treeview
nodes) it but it is not very hard solving it using recursion.
This are basically your three nodes:
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"
}
]
}
]
}
]
}
]
}
];
You can merge it using the following function:
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);
});
}
}
}
}
That merges two nodes in the first one.
And you should invoke it like this:
merge(node1[0], node2[0]);
merge(node1[0], node3[0]);
for your scenario.
NOTE: I'm assuming that you only have one element on each of the nodes (i.e. node0
, node1
and node2
are arrays but they only have one element)
See it running here