Javascript 对象子引用

Javascript Object Child Reference?

本文关键字:引用 对象 Javascript      更新时间:2023-09-26

我有一个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

也不返回任何东西。

下面是 xml 文档的一部分,它被转换为 javascript 对象:

<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/

如果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并没有真正进入它。

在你的问题中:

我有一个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]引用的对象是数组还是对象,在上述方面都没有区别,因为您所追求的属性似乎具有普通对象名称,而不是如果它是数组并用作数组时可能预期的数字索引。

您现在可以找到对象的长度,但索引不会是数字,而是"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*'] 
 }