用String (name)搜索嵌套数组-家谱树数组



我有一个很大的数组,里面包含了8个世纪以来的人名,它非常大,我想建立一个搜索机制,用户可以输入姓名和

  1. 应该搜索嵌套数组
  2. 以及从那个点一直到原点(名字)应该得到所有的名字。

目前它只是搜索第一个元素与。map,这是可以理解的。一种方法是添加嵌套的。map过滤器,但这不是理想的,项目的数量在数百个。

要求:搜索整个嵌套数组,并从该点向上返回一个新数组。

这是CodeSandbox

您需要遍历整个树并遍历每个兄弟节点以匹配您的搜索。我试过javascript,希望能帮到你。

FamilyTree = [
{
fullname: "Adam1",
children: [
{
fullname: "Adam2",
children: [
{
fullname: "Adam3",
children: [
{
fullname: "Adam4",
children: [],
},
{
fullname: "Adam5",
children: [
{
fullname: "Adam6",
children: [
{
fullname: "Adam7",
children: [],
},
],
},
{
fullname: "Adam8",
children: [
{
fullname: "Adam9",
children: [
{
fullname: "Adam10",
children: [],
},
{
fullname: "Adam11",
children: [],
},
],
},
{
fullname: "Adam12",
children: [
{
fullname: "Adam13",
children: [],
},
{
fullname: "Adam14",
children: [],
},
{
fullname: "Adam15",
children: [
{
fullname: "Adam16",
children: [],
},
{
fullname: "Adam17",
children: [],
},
{
fullname: "Adam18",
children: [
{
fullname: "Adam19",
children: [],
},
{
fullname: "Adam20",
children: [],
},
{
fullname: "Adam21",
children: [
{
fullname: "Adam22",
children: [],
},
],
},
],
},
{
fullname: "Adam23",
children: [
{
fullname: "Adam24",
children: [
{
fullname: "Adam25",
children: [
{
fullname: "Adam26",
children: [
{
fullname: "Adam27",
children: [
{ fullname: "Adam28" },
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
],
},
];
tree = [];
function isTheItem(item, searchTerm) {
tree.push(item.fullname);
// console.log('item', item, searchTerm);
return item.fullname.toLowerCase() === searchTerm.toLowerCase();  // condition to identify the children
}
function walk(collection, searchTerm) {
return collection.find(item => isTheItem(item, searchTerm) || walk(item.children, searchTerm));
}
function execute(collection, searchTerm) {
tree = []
walk(collection, searchTerm);
}
execute(FamilyTree, 'Adam6');
console.log(tree);

相关内容

  • 没有找到相关文章

最新更新