gpt4 book ai didi

javascript - 在 Typescript/Javascript 中过滤掉深度嵌套数据结构的对象

转载 作者:行者123 更新时间:2023-11-30 19:23:23 25 4
gpt4 key购买 nike

我想从一个深度嵌套的数据结构中过滤掉所有匹配规则的对象。我知道有类似的例子可以删除嵌套对象的特定键,但我无法实现解决方案。数据结构永远不会无限大,但可以很深(超过10层)

以下是类型:

    export type DataStructure = Entry[]

export interface Entry {
id: string
text: string
type: 1 | 2
children?: Entry[]
}

所以一个条目数组可以是:

[
{
id: "1",
type: 1,
text: "Node 1",
children: [
{
id: "1.1",
type: 1,
text: "Node 1.1",
children: [
{
id: "1.1.1",
type: 2,
text: "Node 1.1.1",
children: []
}
],
},
{
id: "1.2",
type: 1,
text: "Node 1.2",
children: [
{
id: "1.2.1",
type: 2,
text: "Node 1.2.1",
children: [],
},
{
id: "1.2.2",
type: 1,
text: "Node 1.2.2",
children: [],
}
]
}
]
}
]

预期的输出数组,假设规则 type !== 2 将是:

[
{
id: "1",
type: 1,
text: "Node 1",
children: [
{
id: "1.2",
type: 1,
text: "Node 1.2",
children: [
{
id: "1.2.2",
type: 1,
text: "Node 1.2.2",
children: [],
}
]
}
]
}
]

我无法实现递归来完成它,数组一直显示所有条目如果有内置函数,我不介意使用 lodash。谢谢!

最佳答案

如果你想根据类型进行过滤:

function test() {
const test = [
{
id: "1",
type: 1,
text: "Node 1",
children: [
{
id: "1.1",
type: 1,
text: "Node 1.1",
children: [
{
id: "1.1.1",
type: 1,
text: "Node 1.1.1",
children: []
}
],
},
{
id: "1.2",
type: 2,
text: "Node 1.2",
children: [
{
id: "1.2.1",
type: 2,
text: "Node 1.2.1",
children: [],
},
{
id: "1.2.2",
type: 2,
text: "Node 1.2.2",
children: [],
}
]
}
]
}
];

console.log(JSON.stringify(filterData(test, 2), 0, 4))

console.log('test: ', test);

}

和过滤方法:

function filterData(data, type) {
var r = data.filter(function(o) {
if (o.children)
o.children = filterData(o.children, type);
return o.type != type
})
return r;
}

关于javascript - 在 Typescript/Javascript 中过滤掉深度嵌套数据结构的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57201775/

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