如何在JavaScript中使用动态键值解析JSON

时间:2017-11-28 15:10:00

标签: javascript arrays json

我有一个带动态键值的JSON数组(房间号,每次运行代码时它都会改变)。我想知道如何使用此键值访问内部JSON数组。这是我尝试过的,它会引发错误。

JSON数组(数据)

domain

访问代码

[{"6011":
 [{"occupancy":"2","time":"2017-11-10 00:00:00"},
 {"occupancy":"1","time":"2017-11-10 00:30:00"},
 {"occupancy":"2","time":"2017-11-10 01:00:00"}]
}]

2 个答案:

答案 0 :(得分:1)

您的对象位于数组中,因此您应该使用jsonObject将代码指向数组[0]的第一列,如:

var innerArray = jsonObject[0][room];

希望这有帮助。



var data = [{
  "6011": [{
      "occupancy": "2",
      "time": "2017-11-10 00:00:00"
    },
    {
      "occupancy": "1",
      "time": "2017-11-10 00:30:00"
    },
    {
      "occupancy": "2",
      "time": "2017-11-10 01:00:00"
    }
  ]
}];

var room = "6011";
var jsonObject = jQuery.parseJSON(JSON.stringify(data));
var innerArray = jsonObject[0][room];

console.log(innerArray);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

假设room的值为6011"6011",并假设{"6011": ... }并不总是数组中的唯一对象,则需要首先是find对象,因为你的对象被包装在一个数组中。然后,您可以[room]访问房产。

&#13;
&#13;
var jsonObject = [{ "6011": [{ "occupancy": "2", "time": "2017-11-10 00:00:00" }, { "occupancy": "1", "time": "2017-11-10 00:30:00" }, { "occupancy": "2", "time": "2017-11-10 01:00:00" } ] }, { "6012": [{ "occupancy": "2", "time": "2017-11-10 00:00:00" }, { "occupancy": "1", "time": "2017-11-10 00:30:00" }, { "occupancy": "2", "time": "2017-11-10 01:00:00" } ] }],
  room = 6011;

var foundObject = jsonObject.find(obj => obj.hasOwnProperty(room));

console.log(foundObject && foundObject[room]);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;