[英]Javascript: Get a reference from JSON object with traverse
我需要從JSON對象獲取引用,代碼如下:
var Tree = { data: { 0: { pk: 1, }, 1: { pk: 2, }, 2: { pk: 3, children: { 0: { pk: 11, }, 1: { pk: 22, }, 2: { pk: 33, }, }, }, }, traverse: function(data, pk) { for (i in data) { // console.log(data[i]); if(data[i].pk && data[i].pk == pk) return data[i]; if (typeof(data[i].children) == 'object') this.traverse(data[i].children, pk); }; }, }
遍歷頂層項目時,該代碼非常有效:
>>> Tree.traverse(Tree.data, 1); Object {pk=1}
但是在獲取子元素時壞了:
>>> Tree.traverse(Tree.data, 22); undefined
當您取消注釋“ // console.log(data [i]);”時,為什么會出現這種行為我感到非常奇怪。 行,您將看到對象已獲得但未返回。
有什么想法嗎?
你沒有把return
前this.traverse(data[i].children, pk);
。
編輯:
var Tree = {
data: {
0: {
pk: 1,
},
1: {
pk: 2,
},
2: {
pk: 3,
children: {
0: {
pk: 11,
},
1: {
pk: 22,
},
2: {
pk: 33,
},
},
},
},
traverse: function(data, pk) {
for (var i in data) {
// console.log(data[i]);
if(data[i].pk && data[i].pk == pk)
return data[i];
if (typeof(data[i].children) == 'object') {
var retVal = this.traverse(data[i].children, pk);
if (typeof retVal!='undefined') {//here was the logical problem,there might be more than one
//object, we can't return the result of traversing first one.
//So we will check, if no return, we go on searching
return retVal;
}
}
};
},
};
alert(Tree.traverse(Tree.data, 1).pk);
alert(Tree.traverse(Tree.data, 22).pk);
在此處查看直播: http : //jsfiddle.net/rq4LK/
這是一個遠景,但是您正在for
循環中創建全局變量。 嘗試for(var i in data)
代替,然后報告。
在這種情況下不整的對象和你的物業設有一個按鍵(如3: ...
)在父Object
並不在存在字面children
子屬性,它顯然會返回undefined
,因為沒有這樣的該鍵的屬性。
編輯:根據您的評論,這可能是函數范圍的問題,因為您正在使用尾部遞歸來遍歷具有多個層的對象。 因此,請像在需要動態引用的任何javascript語言構造中所做的那樣,嘗試將當前對象引用置於函數范圍之外:
var current = null , match = null ;
function traverse() {
var data = arguments[0] ;
var pk = arguments[1] ;
for(var i in data) {
current = data[i] ; /* DEBUG */console.log( current.toSource() ) ; //!! Object.prototype.toSource() requires a W3 compatible browser (like FF)
if(current.pk !== undefined && current.pk === pk) return current ;
else if( typeof current.children === "object") traverse(current.children, pk);
}
}
match = traverse(data,pk) ;
編輯2:我的邏輯有缺陷。 嘗試以下方法:
var match = null ;
function traverse() {
var data = arguments[0] ;
var pk = arguments[1] ;
var current = null ;
for(var i in data) {
current = data[i] ; /* DEBUG */console.log( current.toSource() ) ; //!! Object.prototype.toSource() requires a W3 compatible browser (like FF)
if(current.pk !== undefined && current.pk === pk) match = current ; //!! if there is a match set the variable match to the current object
else if( typeof current.children === "object") traverse(current.children, pk); //!! else use recursion to test a child property if present
}
}
使用該方法,如果您的對象包含指定的屬性,則match
不會為null
,而是包含匹配的對象或子對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.