[英]MLM binary tree update
我在 javascript 中嵌套了 object ,其中 object 的 id 正在增加深度。 使用 javascript 支持我在 id 中添加和 object - 2 个子数组将为 3,我需要更新(递增)id 树中的所有兄弟姐妹,这只是一个示例代码,它应该适用于每种情况,例如 id: 4 将变成 5 并且它的所有孩子也将更改 id 更改为 6、7、8 等,我们还需要更改父 id,因为 id 正在更改检查,例如下面
(
[id] => 1
[parent_id] =>
[children] => Array
(
[0] => Array
(
[id] => 2
[parent_id] => 1
[children] => Array
(
[0] => Array
(
[id] => 3
[parent_id] => 2
[children] => Array
(
)
)
)
)
[1] => Array
(
[id] => 4
[parent_id] => 1
[children] => Array
(
[0] => Array
(
[id] => 5
[parent_id] => 3
[children] => Array
(
)
)
[1] => Array
(
[id] => 6
[parent_id] => 3
[children] => Array
(
)
)
[2] => Array
(
[id] => 7
[parent_id] => 4
[children] => Array
(
)
)
)
)
[2] => Array
(
[id] => 8
[parent_id] => 1
[children] => Array
(
)
)
)
)
这个简单的递归 function (假设没有父节点的节点的 parentId 为undefined
或null
)应该改变树并增加节点及其所有子节点的 id 和父 id:
const updateIds = (tree) => {
tree.id++;
if (Number.isInteger(tree.parentId)) {
tree.parentId++;
}
tree.children.forEach(child => {
updateIds(child);
})
}
这是 id 递增的 function:
const updateIds = (tree, insertedId) => {
if (tree.id > insertedId) {
tree.id++;
}
if (Number.isInteger(tree.parentId) && tree.parentId > insertedId) {
tree.parentId++;
}
tree.children.forEach(child => {
updateIds(child, insertedId);
})
}
这是我的 function 吹 -
var insId = '';
function updateIds( tree, itemName, newTeam ) {
if ( tree.name === itemName ) {
const childrenLength = tree.children.length;
newTeam.id = tree.id + childrenLength + 1;
insId = tree.id + childrenLength + 1;
tree.children = [ ...tree.children, newTeam ];
}
if ( insId !== '' && tree.id >= insId && tree.name !== newTeam.name ) {
tree.id++;
}
if ( insId !== '' && Number.isInteger(tree.parent_id) && tree.parent_id >= insId && tree.name !== newTeam.name) {
tree.parent_id++;
}
tree.children.forEach(child => {
updateIds(child, itemName, newTeam );
});
return tree;
}
一切都很好,直到只有一个案例 senario,比如在根处添加兄弟元素,所以它不会更新这个兄弟元素的 id
如果有人正在寻找对我有用的此类问题,请在下面添加项目部分是解决方案
function depthItem( element ) {
let children = '';
if ( element.children.length > 0 ) {
children = element.children[ element.children.length - 1 ];
return depthItem( children );
}
return element;}
function addNestedItem( array, itemName, newTeam ) {
array.forEach( ( element ) => {
if ( element.name === itemName ) {
const lastItem = depthItem( element );
newTeam.id = lastItem.id + 1;
element.children = [ ...element.children, newTeam ];
} else {
return addNestedItem( element.children, itemName, newTeam );
}
} );
return array;}
function updgradeNestedItemIndex( array, newTeam ) {
array.forEach( ( element ) => {
if ( element.id >= newTeam.id && element.name !== newTeam.name ) {
element.id++;
}
return updgradeNestedItemIndex( element.children, newTeam );
} );
return array;}
const tempTree = addNestedItem( [ tree ], team.name, newTeam );
const newTree = updgradeNestedItemIndex( tempTree, newTeam );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.