假定一个接口,例如:
interface CustomNode {
id: string;
children: CustomNode[];
}
如果我有一个对象,例如:
nodes: CustomNode[] = [
{
id: 'A',
children: [
{
id: 'B',
children: [
{
id: 'C',
children: [
{
id: 'D',
children: []
},
{
id: 'E',
children: []
}
]
}
]
}
]
}
]
我如何创建一个函数来删除给定的“ CustomNode”及其子级?
我更喜欢Typescript / ES6解决方案,但可以使用任何通用解决方案(例如Typescript,Javascript,ES,诸如lodash之类的依赖项)
例如如何删除ID为'C'的CustomNode及其子级?
nodes = removeIfExists(nodes, 'C');
removeIfExists(nodes: CustomNode[], removeId: string) {
// ...
}
答案 0 :(得分:3)
假设您不想更改现有数组或其任何节点,并假设您正在一个节点数组而不是一个节点上进行操作(看起来就是您想要的),则可以编写它像这样:
function removeIfExists(nodes: CustomNode[], removeId: string): CustomNode[] {
return nodes.
filter(n => n.id !== removeId).
map(n => ({ id: n.id, children: removeIfExists(n.children, removeId) }));
}
我们将删除所有具有违规ID的条目,然后递归映射其余节点。让我们确保它适用于您的示例(我将其重命名为nodes
):
const newNodes = removeIfExists(nodes, "C");
console.log(JSON.stringify(newNodes));
//[{ "id": "A", "children": [{ "id": "B", "children": [] }] }]
对我很好。希望能有所帮助;祝你好运!
答案 1 :(得分:0)
一个例子:
var array = [['firstItem','secondItem'],['thirdItem','fourthItem']];
array[0][1] = null;
array = [['firstItem','secondItem'],['thirdItem','lastItem']];
array[0][1] = null;
document.getElementById('demo').innerHTML = array[0][1]
<html>
<p id="demo"></p>
</html>
答案 2 :(得分:0)
如果您要创建新的CustomNode[]
,最快的方法是:
function removeIfExists(nodes: CustomNode[], removeId: string): CustomNode[] {
let res: CustomNode[] = [];
for (const node of nodes) {
if (node.id === removeId) {
continue;
}
res.push({
id: node.id,
children: removeIfExists(node.children, removeId),
})
}
return res;
}
如果要修改当前对象,可以执行以下操作:
function removeIfExists(nodes: CustomNode[], removeId: string): CustomNode[] {
let i = 0;
while (i < nodes.length) {
if (nodes[i].id === removeId) {
nodes.splice(i, 1);
continue;
}
removeIfExists(nodes[i].children, removeId);
++i;
}
return nodes;
}