gpt4 book ai didi

javascript - 在 Reactjs 中递归构建数组

转载 作者:行者123 更新时间:2023-11-30 10:59:51 27 4
gpt4 key购买 nike

我正在尝试从 React 中获取的数组创建一个 menuTree。我的问题是我不知道如何递归地构建我的数组:

假设我获取了一个 mainUrl 并获取了数组:

[
{"id":"EU","type":"l","text":"Europe"},
{"id":"AS","type":"l","text":"Asia"}
]

因为类型是“l”我需要做另一个获取:mainUrl/EU

现在我得到:

[
{"id":"SP","type":"l","text":"Spain"},
{"id":"FR","type":"l","text":"France"}
]

同样,这两种类型都是“l”,所以我进行了另一次获取:mainUrl/EU/SP

现在我得到:

[
{"id":"MA","type":"t","text":"Madrid"}
]

由于类型现在是“t”,我停下来重新开始法国和亚洲。

请记住,我不知道他们在数组中的 child 的部门

我的数组应该是这样的:

[
{
"id": "EU",
"type": "l",
"text": "Europe",
"children": [
{
"id": "SP",
"type": "l",
"text": "Spain",
"children":[
{
"id": "MA",
"type": "t",
"text": "Madrid"
}
]
},
{
"id": "FR",
"type": "l",
"text": "France",
"children": [
{
"id": "PA",
"type": "t",
"text": "Paris"
}
]
}
]
},
{
"id": "AS",
"type": "l",
"text": "Asia",
"children":[...]
}
]

最佳答案

const mainUrl = "yourMainUrl"; 

const fetchDataTree = async url => {

// I assume you will handle the fetch with your own method
let countryArr = await yourFetchFunction(url);

for (let key in countryArr) {
if (countryArr[key].type === "l") {
countryArr[key].children = await fetchDataTree(url + "/" + countryArr[key].id)
}
}

return countryArr
}

const yourDataTree = await fetchDataTree(mainUrl);

关于javascript - 在 Reactjs 中递归构建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58286212/

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