2012-04-29 114 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*'] 
}