gpt4 book ai didi

javascript - array.push 不适用于嵌套 JSON 对象

转载 作者:行者123 更新时间:2023-12-02 16:39:32 25 4
gpt4 key购买 nike

我正在尝试做几件事:

  1. 获取 JSON 数据并将其推送到名为“houses”的数组中。
  2. 访问“houses”中嵌套的数据,并将其推送到名为“values”的新数组中(稍后我将在 d3 可视化中使用“values”)。

我的 JSON 格式如下:

    [
{
"devices": [
{
"device_mac": "0c2a690462c6",
"device_type": "kettle",
"values": [
{
"the_time": "2014-09-22 16:57:19",
"is_active": "1"
},
{
"the_time": "2014-10-08 07:05:52",
"is_active": "0"
},
{
"the_time": "2014-09-27 15:53:10",
"is_active": "1"
}
]
},
{
"device_mac": "0c2a6900446d",
"device_type": "fridge",
"values": [
{ [...]

...等等。基本上有一系列的房子,有一系列的设备,这些设备有一系列的属性和事件附加到它们。

目前,我只是想获取设备的值并将它们插入数组中。这是我当前的代码(其中包括帮助我调试的注释和函数。

var houses = [];
var values = [];

window.onload = function () {
getData();
plotData();
test();
};

function getData() {
$.getJSON("http://dev.modusdeus.com/f_fridge/all_events.php", function (data) {
houses.push(data);
console.log(data[0].devices.device_type);
console.log("getData has run");
});
};

function plotData() {

for (houseIndex in houses) { // what house are we looking at?
var house = [];
house = houses[houseIndex];

for (devicesIndex in house) { // what devices are we looking at?
var devices = [];
devices = house[devicesIndex]; // device's'Index - beware of the 's'

for (deviceIndex in devices) { // what specific device are we looking at?
var device = [];
device = devices[deviceIndex];

for (valueIndex in device[0].values) { // what are the values associated with this device?
var xValue = [];
var yValue = [];

xValue = (device[0].values[valueIndex].the_time);
yValue = (device[0].values[valueIndex].is_active);

values.push([xValue, yValue]);

}
}
}
}
console.log("plotData has run");
console.log(values[0]);
};

function test() {
console.log(typeof houses);
console.log(typeof values);
console.log("test has run");
};

我在控制台日志上不断得到的输出如下:

plotData has run (16:25:13:673)
at public_html/js/main.js:51
undefined (16:25:13:674)
at public_html/js/main.js:52
object (16:25:13:674)
at public_html/js/main.js:56
object (16:25:13:674)
at public_html/js/main.js:57
test has run (16:25:13:675)
at public_html/js/main.js:58
undefined (16:25:15:452)
at public_html/js/main.js:19
getData has run (16:25:15:453)
at public_html/js/main.js:20

这对于我的要求来说是正确的,但如果我问..

console.log(houses)

..我什么也没得到。如果我更具体的话,比如

console.log(houses[0][0])

我刚刚收到一个错误。通常 -

Uncaught TypeError: Cannot read property '0' of undefined

我不知道这是否只是我的语法错误,或者我是否完全走错了路,所以任何帮助都会很棒。我还注意到,在控制台中,某些功能似乎比其他功能先完成,所以这可能是一个问题?

我对此还很陌生,因此对任何明显的疏忽表示歉意,并提前感谢您的帮助。

最佳答案

不要对数组使用for in,而是使用for循环。 for in 用于对象而不是数组

  for (var houseIndex = 0 ; houseIndex < houses.length; houseIndex++) {

// your code
}

关于javascript - array.push 不适用于嵌套 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27624842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com