我正面臨一個算法概念問題。使用JavaScript語言,我有大約11000行的繁重的JSON對象,這是HTML文件轉換的結果。 JSON的結構類似於DOM中的一個,這意味着一個Object可以擁有一個屬性的孩子,這是一個由其他類似對象組成的數據結構。目標是在JSON中搜索並提取具有該屬性的對象的屬性itemprop的信息。 itemprop屬性是在和Object裏面的屬性屬性,表示某些第一個提到的Object有。JavaScript中的遞歸重搜索JSON
對象結構
{ 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](http://json.org/)中搜索,真的嗎?它看起來像一個對象,你正在努力。請添加結構,至少少量,結構如何。 –
你實際上是在尋找字符串「itemprop」嗎? – epascarello
@NinaScholz JSON對象被轉換爲JS對象,不是嗎?我添加了對象結構。一個對象可以有屬性或子屬性。 – amazingcode12