使用JavaScript进行递归以搜索大量JSON

amazingcode12

我面临一个算法概念问题。使用JavaScript语言,我有一个约11000行的沉重JSON对象,这是HTML文件转换的结果。的JSON的结构是类似的DOM中的所述一个,这意味着一个对象可具有属性儿童,其它类似的对象组成的数据结构。目的是在JSON中搜索并提取具有该属性的Object的属性itemprop的信息itemprop属性是和对象内部的属性的属性,一些第一提及的目的有。

对象结构

{ type: 'x',
  tagName: 'y',
  attributes: { "itemprop" : "valueWanted" },
  children:
   [ Object, Object, Object] 
}

我想到了一种递归算法来解决。不幸的是,我对递归不熟悉,下一个代码不起作用。

递归算法

var searchAttributesRecursive = function(children) {
    for (var i = 0; i < children.length; ++i) {
      if (children[i].hasOwnProperty('children')) {
        return searchAttributesRecursive(children[i].children);
      }
      else {
        if (children[i].hasOwnProperty('attributes')) {
            if (children[i].attributes.itemprop === "valueWanted") {
              console.log('success')
            }

          }
        }
        return; // probably a problem that breaks the loop
      }
    };

searchAttributesRecursive(startingChildren);

也许还有另一种更有效的通用算法可以完成此任务。我愿意提出建议。

更新资料

感谢您提供的所有解决方案和说明。更具体地说,请看@ChrisG的简单解决方案。现在,我想在算法中添加一个特殊条件。

如果我想从下一个对象中检索数据,而该对象不在具有对象WantedValue2的子级范围内,那么您是否知道如何访问此数据?该算法在特殊情况下会满足wantValue2,并且不想直接提取itemprop的数据。

对象结构特例

{
 "type": "",
  "tagName": "",
  "attributes": {
  "itemprop": "wantedValue"
   },
  "children": [{
      "type": "",
      "content": ""
      }
    ]
  },
 {
  "type": "",
  "content": ""
  }]
  },         
   {
  "type": "",
  "tagName": "",
  "attributes": {},
  "children": [
  {
   "type": "",
    "content": "here"
   }
  ]
克里斯·G

这是一个简短的版本:

请注意,该函数需要一个数组,因此,如果您的对象不是数组,则必须使用 findItemprop([dom], "wanted")

function findItemprop(data, value, found) {
  if (!found) found = [];
  data.forEach((node) => {
    if (node.attributes && node.attributes.itemprop == value)
      found.push(node);
    if (node.children) findItemprop(node.children, value, found);
  });
  return found;
}

var dom = [{
  tag: "root",
  children: [{
    tag: "header",
    children: [{
      tag: "div"
    }]
  }, {
    tag: "div",
    id: "main",
    children: [{
      tag: "p",
      attributes: {
        itemprop: "wanted"
      }
    }]
  }, {
    tag: "footer",
    children: [{
      tag: "span",
      content: "copyright 2017",
      attributes: {
        itemprop: "wanted"
      }
    }]
  }]
}];

console.log(findItemprop(dom, "wanted"));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章