gpt4 book ai didi

javascript - 用于访问嵌套数组中元素的递归函数和 Map

转载 作者:行者123 更新时间:2023-11-28 17:37:52 25 4
gpt4 key购买 nike

情况

  • 我有一个嵌套数组,并且有一个要搜索的 ID。类似于“A_02_02_01_03”
  • 数组中的每个元素都有一个称为“子元素”的元素,即数组
  • 当我在第 4 层搜索时,我的方法会变得相当长。

数组示例

var tree= [
{
"name": "i2",
"children": [
{
"name": "d1",
"children": [],
"id": "DW_02_01",
"beschreibung": "",
"table": []
},
{
"name": "d2",
"children": [
{
"name": "e1",
"children": [
{
"name": "a1",
"children": [],
"id": "A_02_02_01_01",
"beschreibung": "",
"table": []
},
{
"name": "a2",
"children": [],
"id": "A_02_02_01_02",
"beschreibung": "",
"table": []
},
{
"name": "a3",
"children": [],
"id": "A_02_02_01_03",
"beschreibung": "",
"table": []
}`enter code here`
],
"id": "E_02_02_01",
"beschreibung": "",
"table": []
},
{
"name": "e2",
"children": [],
"id": "E_02_02_02",
"beschreibung": "",
"table": []
}
],
"id": "DW_02_02",
"beschreibung": "",
"table": []
},
{
"name": "d3",
"children": [],
"id": "DW_02_03",
"beschreibung": "",
"table": []
}
],
"id": "IW_02",
"beschreibung": "",
"table": []
},
{
"name": "i3",
"children": [],
"id": "IW_03",
"beschreibung": "",
"table": []
}
]

构造 ID

var daIW = "IW_02";
var daDW = "DW_02_02;
var daE = "E_02_02_01;
var daA = "A_02_02_01_03";

获取我的所有索引

var iw_index = tree.findIndex(element => element.id == daIW);
var dw_index = tree[iw_index]["children"].findIndex(element => element.id == daDW);
var e_index = tree[iw_index]["children"][dw_index]["children"].findIndex(element => element.id == daE);
var a_index = tree[iw_index]["children"][dw_index]["children"][e_index]["children"].findIndex(element => element.id == daA);

访问我的元素

var elementName = tree[iw_index]["children"][dw_index]["children"][e_index]["children"][a_index].name;

问题

是否有更短的方法来访问最深的元素“A_02_02_01_03”然后搜索每个索引?

最佳答案

您可能希望递归首先深入搜索树:

function search(array = [], id){
for(const node of array){
if(node.id === id) return node;

const sub = search(node.children, id);
if(sub) return sub;
}
}

所以你可以这样做:

const result = search(tree, "A_02_02_01_03");
<小时/>

如果你想查找多个项目,最好建立一个存储所有 id/node 对的哈希表,这样查找速度非常快:

function createLookup(array, hash = new Map){
for(const node of array){
hash.set(node.id, node);
createLookup(node.children, hash);
}
return hash;
}

所以你可以这样做:

const hash = createLookup(tree);
const result = hash.get("A_02_02_01_03");

关于javascript - 用于访问嵌套数组中元素的递归函数和 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48668232/

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