gpt4 book ai didi

javascript - 如何过滤/搜索返回父子关系的嵌套树

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

我有一个看起来像这样的嵌套列表:

list = {
"name": "first",
"children": [
"name" : "second",
"children" : [
"name" : "third",
"children" : [...could be nested infinitly]
]
],
"name": "a",
"children": [
"name" : "b",
"children" : [
"name" : "c",
"children" : [...could be nested infinitly]
]
],
"name": "test",
"children": [
"name" : "testChild",
"children" : [
"name" : "grandChild",
"children" : [...could be nested infinitly]
]
]

我正在努力解决的问题是在 javascript 中使用 AND OR CONTAINS 进行查询/过滤/搜索的最佳方式,与此类似:

姓名包含 a AND children > 2 OR name = grandchild

哪个会返回:

newList = {
"name": "a",
"children": [
"name" : "b",
"children" : [
"name" : "c",
"children" : [...could be nested infinitly]
]
],
"name": "test",
"children": [
"name" : "testChild",
"children" : [
"name" : "grandChild",
"children" : [...could be nested infinitly]
]
]

最佳答案

您可以为 child 使用约束函数和迭代递归方法。结果集返回第一个匹配所有属性的节点。

function getList(array, constraint) {
var result = [];
array.forEach(function iter(a) {
constraint(a) && result.push(a);
Array.isArray(a.children) && a.children.forEach(iter);
});
return result;
}


var list = [{ name: "first", children: [{ name: "second", children: [{ name: "third", children: [] }] }, { name: "a", children: [{ name: "b", children: [{ name: "c", children: [] }] }, { name: "test", children: [{ name: "testChild", children: [{ name: "grandChild", children: [] }] }] }] }] }],
constraint = function (o) {
return o.name.indexOf('a') !== -1 && (o.children || []).length === 2 || o.name === 'grandChild';
};

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

关于javascript - 如何过滤/搜索返回父子关系的嵌套树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43692367/

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