gpt4 book ai didi

javascript - 递归迭代结构

转载 作者:行者123 更新时间:2023-11-30 00:06:40 24 4
gpt4 key购买 nike

我有以下结构:

var struct = [{
"name": "Name1",
"type": "type1",
"children": [{
"name": "Name11",
"type": "type1",
"children": [{
"name": "Name111",
"type": "type1"
},
{
"name": "Name112",
"type": "type2"
}
}]
}]
}];

我想遍历类型等于 type1 的所有名称类型元素并创建一个 <option>每个元素的元素。

所以它会是这样的:

var iterate = function (data) {
var elements = [];
for (var i in data) {
if (data[i].type == 'type1') {
var option = document.createElement('option');
option.innerHTML = data[i].name;
elements.push(option);
elements.push(iterate(data[i].children));
}
}
return elements;
};

然而,它给了我错误的结果。而且可能效率很低。我应该如何正确执行此操作?

最佳答案

您可以使用迭代递归方法来获取嵌套数据。

function getElements(data) {
var elements = [];
data.forEach(function iter(a) {
var option;
if (a.type === 'type1') {
option = document.createElement('option');
option.innerHTML = a.name;
elements.push(option);
Array.isArray(a.children) && a.children.forEach(iter); // assuming only
} // type1 branches
}); // to iterate
return elements;
}

var struct = [{ "name": "Name1", "type": "type1", "children": [{ "name": "Name11", "type": "type1", "children": [{ "name": "Name111", "type": "type1" }, { "name": "Name112", "type": "type2" }] }] }];

console.log(getElements(struct));

关于javascript - 递归迭代结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38244913/

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