【发布时间】:2017-11-04 07:49:01
【问题描述】:
我正面临一个算法概念问题。使用 JavaScript 语言,我有一个大约 11 000 行的重型 JSON 对象,这是 HTML 文件转换的结果。 JSON的结构类似于DOM的结构,也就是说一个Object可以有一个属性children,一个由其他类似Object组成的数据结构。目标是在 JSON 中搜索并提取具有该属性的 Object 的属性 itemprop 的信息。 itemprop 属性位于 attributes 属性中的 Object 中,其中一些第一次提到的 Object 具有。
对象结构
{ 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 的子对象范围之外,您知道如何访问这些数据吗?该算法会有一个特殊情况,它满足wantedValue2,并且不想直接提取itemprop的数据。
对象结构特例
{
"type": "",
"tagName": "",
"attributes": {
"itemprop": "wantedValue"
},
"children": [{
"type": "",
"content": ""
}
]
},
{
"type": "",
"content": ""
}]
},
{
"type": "",
"tagName": "",
"attributes": {},
"children": [
{
"type": "",
"content": "here"
}
]
【问题讨论】:
-
搜索JSON,真的吗?它看起来像一个对象,你正在处理。请添加结构,至少少量,它的结构。
-
你真的在寻找字符串“itemprop”吗?
-
@NinaScholz JSON 对象被转换为 JS 对象,不是吗?我添加了对象结构。一个 Object 可以有 attributes 或 children 属性。
-
@epascarello 是的。
-
正如 Nina 所链接的,JSON 只是一种文本格式。这是一个字符串。除了
JSON内置 JavaScript 对象之外,没有“JSON 对象”之类的东西。但是是的,JSON.parse确实将 JSON 字符串转换为 JavaScript 对象。这是一个很小但很重要的区别。
标签: javascript json algorithm recursion bigdata