gpt4 book ai didi

javascript - 如果选择了所有子节点,如何将父树节点标记为已选择

转载 作者:行者123 更新时间:2023-11-30 13:50:43 24 4
gpt4 key购买 nike

我有一个形成树的 json。

[{
id: 1,
name: "A",
isSelected: false,
child: [
{
id: 2,
name: "B",
isSelected: false,
}
{
id: 3,
name: "C",
isSelected: false,
}
]
},
{
id: 4,
name: "D",
isSelected: false,
child: [
{
id: 5,
name: "E",
isSelected: false,
}
{
id: 6,
name: "F",
isSelected: false,
}
]
}]

现在我有一个选定节点的数组

[{id: 2},{id:3}]

markSelectedNodes方法根据选中的节点数组将节点标记为选中

markSelectedNodes(_nodes) {
_nodes.forEach((_node) => {
// match if node exists in selected nodes
const _isFound = this.selectedNodes.find((_selectedNode) => _selectedNode.id === _node.id);
if (_isFound) {
_node.isSelected = true;
} else {
_node.isSelected = false;
}
// removed the node from selecedNode list as this has been marked selected
this.selectedNodes = this.selectedNodes.filter((_selectedNode) => _selectedNode !== _node.id);

// go through the child
if (_node.child && _node.child.length) {
this.markSelectedNodes(_node.child);
}
});
}

现在如果所有子节点都被标记为选中,它也应该将父节点标记为选中。

这个可以通过stack来实现吗?

最佳答案

您可以采用迭代和递归的方法并检查是否选择了每个项目来更新父节点。

function update(array = [], ids) {
return !!array.length
&& array.every(node => node.isSelected = ids.includes(node.id) || update(node.child, ids));
}

var data = [{ id: 1, name: "A", isSelected: false, child: [{ id: 2, name: "B", isSelected: false }, { id: 3, name: "C", isSelected: false }] }, { id: 4, name: "D", isSelected: false, child: [{ id: 5, name: "E", isSelected: false }, { id: 6, name: "F", isSelected: false }] }],
nodes = [{ id: 2 }, { id: 3 }];

update(data, nodes.map(({ id }) => id));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果需要迭代所有嵌套数组,可以存储标志,迭代并返回迭代结果。

function update(array = [], ids) {
if (!array.length) return false;
var selected = true;
array.forEach(node => {
node.isSelected = ids.includes(node.id) || update(node.child, ids);
selected = selected && node.isSelected;
});
return selected;
}

var data = [{ id: 1, name: "A", isSelected: false, child: [{ id: 2, name: "B", isSelected: false }, { id: 3, name: "C", isSelected: false }] }, { id: 4, name: "D", isSelected: true, child: [{ id: 5, name: "E", isSelected: true }, { id: 6, name: "F", isSelected: true }] }],
nodes = [{ id: 2 }, { id: 3 }];

update(data, nodes.map(({ id }) => id));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如果选择了所有子节点,如何将父树节点标记为已选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58299392/

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