访问json数组元素的动态方式

dynamic way to access json array elements

本文关键字:动态 方式 数组元素 json 访问      更新时间:2023-09-26

所以我有json数组

data = '[{"beatles": [
                {"name":"Paul McCartney","value": "http://www.paulmccartney.com"},
                {"name": "John Lennon","value": "http://www.johnlennon.it"},
                {"name":"George Harrison","value": "http://www.georgeharrison.com"},
                {"name": "Ringo Starr","value": "http://www.ringostarr.com"}],
           "stones": [
                {"name": "Mick Jagger","value": "http://www.mickjagger.com"},
                {"name": "Keith Richards","value": "http://www.keithrichards.com"}]'

我有两个下拉列表

<html xmlns="http://www.w3.org/1999/xhtml">
     <head>
          <title></title>
          <script src="rockbands.json"></script>
          <script src="script.js"></script>
     </head>
     <body onload="getBands()">
          <select id="bands" onchange="getNames(this.value)"></select>
          <select id="names" ></select>
     </body>
</html>

所以我用这个JS代码加载ID为"bands"的下载列表

function getBands() {
    var root = JSON.parse(data)
    var bandsBox = document.getElementById("bands")
    for(i in root[0]) {
        var option = document.createElement("option")
        option.text = i
        bandsBox.appendChild(option)
    }
}

我想做的是用ID"name"填充另一个下拉列表数组元素"name"基于第一个下拉列表中的选择,例如,如果我选择beatles,它将加载beatles 中的所有名称

我可以用root[0].beatles[1].name之类的东西访问它,但我想要一种动态的方式来访问它们,这要归功于

getNames()函数中执行类似的操作

function getNames(nameOfBand) {
    var root = JSON.parse(data);
    var namesBox = document.getElementById("names");
    var listOfNames = root[0][nameOfBand]
    for( j = 0; j < listOfNames.length; j++) {
        var option = document.createElement("option");
        option.text = listOfNames[j]["name"];
        namesBox.appendChild(option)
    }
}

基于此文档:

属性访问器通过使用提供对对象属性的访问点表示法或括号表示法。

object.property
object["property"]

这意味着您也可以访问root[0]['beatles'][1]['name']等属性。

由于"beatles"是一个类似属性的字符串,它也可以是一个变量:

root[0][band_name][1]['name']