递归DOM转JSON函数排除指定属性节点时返回undefined问题
修复DOM转JSON时排除节点的问题
你的代码核心问题是:带有data-exclude属性的节点返回undefined后,子节点遍历逻辑直接将这个undefined存入了childNodes数组,导致输出结果包含无效值。同时代码中存在未声明的全局变量length,需要一并修复。
修改要点
- 明确排除节点时返回
undefined(增强代码可读性) - 遍历子节点时,仅将递归调用后非undefined的结果加入
childNodes数组 - 修复未声明的
length变量,避免全局污染
修改后的完整代码
const htmlToJSON = node => { const exclude = node.attributes?.getNamedItem('data-exclude'); if (exclude) { // 明确返回undefined,标记该节点需要排除 return undefined; } let obj = { nodeType: node.nodeType }; if (node.tagName) { obj.tagName = node.tagName.toLowerCase(); } else if (node.nodeName) { obj.nodeName = node.nodeName; } if (node.nodeValue) { obj.nodeValue = node.nodeValue; } const attrs = node.attributes; if (attrs) { // 修复未声明的length变量 const length = attrs.length; const arr = (obj.attributes = new Array(length)); for (let i = 0; i < length; i++) { const attr = attrs[i]; arr[i] = [attr.nodeName, attr.nodeValue]; } } const childNodes = node.childNodes; if (childNodes && childNodes.length) { let arr = (obj.childNodes = []); for (let i = 0; i < childNodes.length; i++) { const childResult = htmlToJSON(childNodes[i]); // 仅保留有效节点,过滤undefined if (childResult !== undefined) { arr.push(childResult); } } } return obj; }; const parser = new DOMParser(); const { body } = parser.parseFromString(page, 'text/html'); let jsonOutput = htmlToJSON(body); console.log(jsonOutput);
关键逻辑说明
- 排除节点处理:当检测到
data-exclude属性时,直接返回undefined,明确标记该节点需要被排除。 - 子节点过滤:在遍历子节点时,先递归调用
htmlToJSON得到结果,只有当结果不为undefined时,才将其添加到childNodes数组中,彻底移除被排除的节点。 - 变量修复:给
length添加const声明,避免全局变量污染,符合严格模式规范。
内容的提问来源于stack exchange,提问作者AndyJamesN
相关产品推荐
相关产品推荐

