在Typescript/Javascript中过滤出深度嵌套的数据结构中的对象
我想从深度嵌套的数据结构中筛选出与规则匹配的所有对象。我知道有类似的例子可以删除嵌套对象的特定键,但我还没有实现解决方案。数据结构永远不会是无限的,但它可以是非常深的(超过10层) 以下是类型:在Typescript/Javascript中过滤出深度嵌套的数据结构中的对象,javascript,typescript,tree,filtering,Javascript,Typescript,Tree,Filtering,我想从深度嵌套的数据结构中筛选出与规则匹配的所有对象。我知道有类似的例子可以删除嵌套对象的特定键,但我还没有实现解决方案。数据结构永远不会是无限的,但它可以是非常深的(超过10层) 以下是类型: export type DataStructure = Entry[] export interface Entry { id: string text: string type: 1 | 2 children?: Ent
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;
}
“所有符合规则的对象”确切的规则是什么?请证明所有的输入参数和一个示例预期输出策略!我还没写完,就错发了。规则是type!==2
,我已经进行了编辑,以便您可以查看输出。据我所知,o.children
应始终返回true
,因为空数组不是虚假语句。请参阅console.log(!![])=>true
。