我有以下tags
个对象数组:
[
{
"tagName": "Optimizely Setup",
"children": [],
},
{
"tagName": "Adobe DTM Bootstrap",
"children": [
{
"tagName": "Adobe Analytics",
"children": [
{
"tagName": "Adobe Analytics",
"children": []
}
]
}
]
},
{
"tagName": "Google Content Experiments",
"children": []
},
{
"tagName": "Google Tag Manager",
"children": []
},
{
"tagName": null,
"children": [
{
"tagName": "Wordpress Stats",
"children": [],
}
]
},
{
"tagName": "AddThis Widget",
"children": [
{
"tagName": "AddThis",
"children": [],
}
]
}
]
我的目标是检查每个对象的tagName
。如您所见,任何对象都可以拥有需要children
检查的嵌套tagName
对象数组。
我正在尝试使用递归函数,但我陷入无限循环......
var tagNameArr = [];
var findObjectByLabel = function(obj) {
for(i = 0; i < obj.length; i++) {
if(obj[i].tagName != null){
var tms = obj[i].tagName.match(/Adobe DTM Bootstrap|Google Tag Manager/g)
if(tms === null) {
tagNameArr.push(obj[i].tagName)
if(obj[i].children.length > 0) {
findObjectByLabel(obj[i].children)
}
}
}
}
return null;
}
findObjectByLabel(tags);
这是我第一次使用递归,任何解决方案都会有很多帮助
发现错误:for
循环缺少变量初始化