2012-04-29 115 views
0

我有一個javascript對象,我需要引用它的一個孩子的價值。孩子應該是數組的一部分。Javascript對象兒童參考?

這工作:

this.manager.response.highlighting[doc.id]['sentence_0002'] 

但這並不:

this.manager.response.highlighting[doc.id][0] 

我不知道哪個sentence_000*號碼將被退回,所以我想引用它通過它的陣列數。

this.manager.response.highlighting[doc.id].length 

也不返回任何東西。

這裏是被闢爲JavaScript對象的XML文檔的一部分:

<response> 
    <lst name="highlighting"> 
    <lst name="http://www.lemonde.fr/international/"> 
     <arr name="sentence_0005"> 
     <str> puni pour sa gestion de la crise Geir Haarde a été condamné pour avoir manqué aux devoirs de sa </str> 

我需要連接在<str>值。 doc.id已成功設置爲http://www.lemonde.fr/international/

+0

這將是表現出更多的有用從XML創建的JavaScript對象。 – RobG

回答

0

如果highlighting[doc.id]有像sentence_xyz一個名稱的屬性,有沒有位置,以該財產,但你可以找到鑰匙存在使用什麼for..in循環:

var key, val; 
var obj = this.manager.response.highlighting[doc.id]; 
for (key in obj) { 
    // Here, `key` will be a string, e.g. "sentence_xyz", and you can get its value 
    // using 
    val = obj[key]; 
} 

你可能會發現你需要過濾掉其他屬性,你可以用通常的字符串方法做,如:

for (key in obj) {[ 
    if (key.substring(0, 9) === "sentence_") { 
     // It's a sentence identifier 
    } 
} 

您也可以找到hasOwnProperty有用,但我猜這是一個來自JSON文本響應的反序列化對象圖,在這種情況下,hasOwnProperty並不真正進入它。

+0

@ T.J. Crowder使用key&val就像一個魅力。現在有道理。感謝您的迴應! – Ramsel

+0

@ TJCrowder-如果該值已分配給名爲'sentence_0002'的屬性而不是名爲'0'的屬性,則即使該對象是數組,也不會「工作」。我懷疑這是OP發現用於......的原因。 – RobG

+0

@RobG:是的,不知道我的頭在哪裏,以及「如果它是非數組對象」。無論它是否是數組都沒關係! :-) –

0

在你的問題:

我有一個JavaScript對象,我需要參考它的一個孩子的價值。孩子應該是數組的一部分。

這工作:

this.manager.response.highlighting[doc.id]['sentence_0002'] 

但這並不:

this.manager.response.highlighting[doc.id][0] 

這表明該對象this.manager.response.highlighting[doc.id]引用有一個名爲sentence_0002性質,它不具有屬性名稱爲「0」。

該對象可能是對象或數組(或任何其他對象,如函數或甚至DOM對象)。請注意,在JavaScript中,數組只是具有特殊長度屬性的對象和一些可以大體上應用於任何對象的方便的繼承方法。

因此,通過this.manager.response.highlighting[doc.id]引用的對象是否爲數組或對象,使上面沒有任何區別,因爲屬性你看來以後有一個普通的對象名稱,而不是數字索引,如果它是可以預料一個數組並被用作一個數組。

0

現在你可以找到你的物體的長度,但指數不會是數字,這將是「sentence_000 *」

要做到這一點:

var obj = this.manager.response.highlighting[doc.id], 
    indexes = Object.getOwnPropertyNames(obj),  
    indexLength = indexes.length; 
for(var counter = 0; counter < indexLength; counter++){ 
    obj[indexes[counter]] == val // obj[indexes[counter]] is same as this.manager.response.highlighting[doc.id]['sentence_000*'] 
}