如何在javascript中获取子对象的值

时间:2015-05-04 21:59:25

标签: javascript

我试图获取此对象的子对象的值:

var data = {
    "5d55e9df-08f9-40db-bb46-64721c3b75ab":  {
        "value": "120"
    },
    "e7bc3558-f6b3-4797-ba72-ec9fe84986b2":  {
        "0":  {
            "value": ""
        }
    },
    "bookContent":  {
        "0":  {
            "value": "11 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
        },
        "1":  {
            "value": "remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
        }
    }
}

我如何获得这些值

  1. value下的bookContent媒体资源的价值 - > 1
  2. value
  3. 5d55e9df-08f9-40db-bb46-64721c3b75ab属性的值

    这就是我的尝试:

    var mywantvalue = data[0].bookContent[0].value
    

    但它不起作用 - 我得到"无法获得未定义的值。"

2 个答案:

答案 0 :(得分:1)

您的所有数据都存储在一系列嵌套对象中。对象属性通常由点表示法parent.child)访问,但可以通过方括号表示法parent["child"])访问。

对于包含JS变量/属性名称中无效字符的属性名称,必须使用方括号表示法。

因此,根据您显示的结构,可以检索所需的数据,如

  1. data.bookContent["1"].value
  2. data["5d55e9df-08f9-40db-bb46-64721c3b75ab"].value

答案 1 :(得分:1)

示例数据缺少一些右括号,我假设是复制和粘贴错误。除此之外,可以像这样访问该值:

data.bookContent['1'].value;

运行下面的代码段进行测试。

这不是问题的一部分,但这种格式的节点(即键名0,1,2,3,n)可以很容易地转换为数组(我记得)数组切片方法。关于这样做,有关于SO的帖子。

你知道,这真的不是一个糟糕的问题。我已经在其他数据来源中看到过这种格式,并且它确实会让人们忘记以前没见过的人。



<html>
<body>
VALUE:  data.bookContent['1'].value
<div  id="book"></div>  
 <p>
JSON:
<xmp id="stdout"></xmp>
  
<script type="text/javascript">

  var data = 
{
"5d55e9df-08f9-40db-bb46-64721c3b75ab":  {
    "value": "120"
},
"e7bc3558-f6b3-4797-ba72-ec9fe84986b2":  {
    "0":  {
        "value": ""
    }
},
"bookContent":  {
    "0":  {
        "value": "11 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."
    },
    "1":  {
        "value": "remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
    }
  
  
  }
  };
  

  
document.getElementById('stdout').innerHTML = JSON.stringify(data,null,'  '); 
  
document.getElementById('book').innerHTML = data.bookContent['1'].value;
  
</script>
</body>
</html>
&#13;
&#13;
&#13;