使用变量键访问 JavaScript 对象中的值

密码:

function updateDashboardData() {
$.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
$('.stationContainer').each(function(data) {
var bsID = $(this).attr("id");
var bsStatus = $(this).children('.stationStatus');
alert(data[bsID][0].time);
bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
bsStatus.find('.bs_time').text(data[bsID][0].time);
});
});
}

对象数据:

{
"A5A50000": [{
"bsid": "A5A50000",
"chanCount": 17,
"time": "2009-05-27 16:36:45",
"avgInterference": 1.711765,
"maxInterference": 4.97,
"avgHandsets": 205.1176,
"maxHandsets": 315,
"avgCalls": 6.4118,
"maxCalls": 13,
"avgCBA": 3868.98059,
"maxCBA": 7463,
"sumSuccessCBA": 197318,
"sumTimeoutHandoff": 133,
"sumAttemptHandoff": 1028,
"sumDeniedHandoff": 216,
"sumConfirmHandoff": 679,
"sumHandoffNetwork": 61873,
"sumJoinNetwork": 96888,
"sumLeaveNetwork": 93754,
"sumRcvdKeepalive": 98773,
"sumTimeoutKeepalive": 19748,
"sumAttemptUplink": 93689,
"sumBlockedUplink": 62453
}]
}

问题是:

alert(data.A5A50000[0].time);正确显示“2009-05-2716:36:45”。

alert(bsID);正确显示“ A5A50000”。

alert(data.bsID[0].time);报告“ data.bsID 未定义”。

alert(data[bsID][0].time);报告“ data [ bsID ]未定义”。

我不太清楚什么时候对变量求值[不求值]。也许我忽略了一些愚蠢的事情,但我不能解决我的问题在这里。

126202 次浏览

可以通过点符号或括号符号访问对象属性。

var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi

当你有一个动态值时,你必须使用后者:

var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi

所以你真正想要的是:

alert(data[bsID][0].time);

编辑:

不知道你做错了什么,但是这个在 Firebug 的控制台上对我很有用:

var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]};
var bsID = 'A5A50000';
alert(data[bsID][0].time);

在 Javascript 中,您可以使用对象或数组样式的符号来查找属性:

data.A5A50000
data['A5A50000']

使用第二种语法,可以使用变量代替对象字符串:

data[bsID][0]

我在使用嵌套的 JSON API-response 时遇到了同样的问题:

[
{
"bj_code": "2019",
"BJ_PERIODE": [
{
"nummer": 1
},
{
"nummer": 2
}
]
}
]

我可以评估:

pm.expect(pm.response.json()[0].BJ_PERIODE[1].nummer).to.eql(2);

但是通过变量与 BJ_PERIODEnummer一起工作并不起作用。 即使在这个嵌套的 JSON 中,使用括号方法编写它也可以工作,如下所示:

const periode = "BJ_PERIODE";
const nr = "nummer";
pm.expect(pm.response.json()[0][periode][1][nr]).to.eql(2);