gpt4 book ai didi

javascript - 如何使用 jQuery 访问 json 文件中的这些键和值?

转载 作者:行者123 更新时间:2023-11-28 17:54:02 25 4
gpt4 key购买 nike

我在访问 json 文件中的键和值时遇到问题。我已经尝试了很多事情,但这周我的注意力集中在我身上,但我陷入了困境。

这是我的 Transport.json 文件..

{"transportation":[
{"Springfield":[{
"bus":[{
"start": 6,
"end": 24,
"stops":["oak street", "main street"]
}],
"taxi":[{
"start": 25,
"end": 25,
"stops":["all"]
}]
}]},
{"Pleasantville":[{
"bus":[{
"start": 6,
"end": 22,
"stops":["centre street", "river street"]
}],
"taxi":[{
"start": 25,
"end": 25,
"stops":["all"]
}],
"train":[{
"start": 6,
"end": 23,
"stops":["uptown", "downtown"]
}]
}]}
]}

我想做的两件事是..

  1. 我希望能够提醒用户当前区域的总线起始值。

  2. 我想循环遍历公交车站点以与用户当前站点进行比较。

这是我的 js 代码..

var currentArea = 'Pleasantville'; // this variable changes
var currentStop = 'uptown'; // this variable changes
$.getJSON("transport.json", function(jsontransportation) {
$(jsontransportation.transportation).each(function(dataaaa) {
var areaName = Object.keys(this);
if (areaName == currentArea) { // this works to find correct area in json
$(this.bus).each(function(key, value) { // i can't get this loop to work
alert(this.start); // alerts nothing, no errors
$(this.stops).each(function(key) { // now im trying to loop through keys in 'stops'
if (this.key === currentStop) { // to compare stop to current area
alert('the bus stops here at ' + currentStop); // and alert if there is a stop here
} else {
alert('the bus does not stop here at ' + currentStop); // else alert no stop here
}
})
});
}
});
});

最佳答案

这正是您所需要的。我还更改了代码,以便警报仅显示一次。

$(document).ready(function(){
var currentArea = 'Pleasantville'; // this variable changes
var currentStop = 'uptown'; // this variable changes
$.getJSON("transport.json", function(jsontransportation) {
$(jsontransportation.transportation).each(function(dataaaa) {
var areaName = Object.keys(this);
if (areaName == currentArea) {
var selectedArea = this[currentArea];
var bus = selectedArea[0].bus;
var stops;
$(bus).each(function(keyBus, valueBus) {
alert(this.start);
stops = false;
$(this.stops).each(function(key, valueStops) {
if (valueStops === currentStop) {
stops = true;
}
})
});
if(stops){
alert('the bus stops here at ' + currentStop);
}else{
alert('the bus does not stop here at ' + currentStop); // else alert no stop here
}


}
});
});
});

要解决此问题,请访问 PLUNKR 的链接。

关于javascript - 如何使用 jQuery 访问 json 文件中的这些键和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44858508/

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