實現(xiàn)思路
可以使用遞歸遍歷整個樹形數(shù)組,將每個節(jié)點的id加入到一個數(shù)組中,最后返回這個數(shù)組即可。
數(shù)據(jù)準備
let datas = [
{
id: "1",
pId: "0",
children: [
{
id: "1-1",
pId: "1",
},
],
},
{
id: "2",
pId: "0",
children: [
{
id: "2-1",
pId: "1",
children: [
{
id: "2-1-2",
pId: "2",
},
],
},
],
},
];
代碼實現(xiàn)
方式一
function getAllIds(tree, result) {
//遍歷樹 獲取id數(shù)組
for (const i in tree) {
result.push(tree[i].id); // 遍歷項目滿足條件后的操作
if (tree[i].children) {
//存在子節(jié)點就遞歸
getAllIds(tree[i].children, result);
}
}
return result;
}
獲取結(jié)果
console.log(getAllIds(datas, []), "getAllIds+++++++++");
方式二
function getAllIds(tree) {
let result = [];
if (!Array.isArray(tree)) {
return result;
}
tree.forEach((node) => {
result.push(node.id);
if (Array.isArray(node.children)) {
// result.push(...getAllIds(node.children));
result = result.concat(getAllIds(node.children));
}
});
return result;
}
獲取結(jié)果
console.log(getAllIds(datas), "getAllIds+++++++++");
方式三
function getAllIds(tree, result) {
if (!Array.isArray(tree)) return []; // 如果不是一個數(shù)組,則返回
for (let i = 0; i < tree.length; i++) {
const node = tree[i];
result.push(node.id); // 存儲當前節(jié)點的id
if (Array.isArray(node.children)) {
// 如果當前節(jié)點有子節(jié)點,則遞歸遍歷子節(jié)點
getAllIds(node.children, result);
}
}
return result;
}
獲取結(jié)果
console.log(getAllIds(datas, []), "getAllIds+++++++++");
方法總結(jié)
這里的tree是樹形數(shù)組,result是用來保存所有id的數(shù)組。
首先遍歷當前層級的每個節(jié)點,將節(jié)點的id加入到result中。
如果節(jié)點還有子節(jié)點,就遞歸調(diào)用getAllIds函數(shù)獲取子節(jié)點的id并將其合并到result數(shù)組中。文章來源:http://www.zghlxwxcb.cn/news/detail-511611.html
最后返回result數(shù)組。文章來源地址http://www.zghlxwxcb.cn/news/detail-511611.html
到了這里,關(guān)于js遞歸遍歷樹形結(jié)構(gòu)數(shù)據(jù),獲取所有數(shù)組id集合的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!