gpt4 book ai didi

javascript - 如何从 JavaScript 中的另一个对象数组中的对象数组获取底层属性

转载 作者:行者123 更新时间:2023-12-03 00:13:06 26 4
gpt4 key购买 nike

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>VR train search</title>
<!--
Data provided by https://www.digitraffic.fi/, used under the following license:
Creative Commons Attribution 4.0 International (CC BY 4.0)

Search for train connections through the VR API
https://www.digitraffic.fi/rautatieliikenne/#reittiperusteinen-haku

-->
</head>

<body>
<h3>Train search</h3>

<form>
<p>Ignore the search fields, I have hard-coded the stations in this example to make the code shorter. Just click Search trains.</p>
<label>From:</label>
<input type="text" id="departure_station">
<label>To:</label>
<input type="text" id="arrival_station">
<label>Date (yyyy-mm-dd):</label>
<input type="text" id="departure_date">
<input type="button" value="Search trains" onclick="searchTrains()">
</form>

<div id="onscreen_text"></div>

<script type="text/javascript">

function searchTrains() {

var departure_station = "HKI";
var arrival_station = "TPE";
var departure_date = "2019-02-12";

var xmlhttp = new XMLHttpRequest();
var json;

xmlhttp.onreadystatechange = function() {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
json = xmlhttp.responseText;
listResults(json);
}

if (xmlhttp.readyState == 4 && xmlhttp.status == 404) {
document.getElementById("onscreen_text").innerHTML = "<p>No search results found in the VR API.</p>";
}
}
// Get the data from the API
xmlhttp.open(
"GET", "https://rata.digitraffic.fi/api/v1/live-trains/station/" + departure_station + "/" + arrival_station + "?" + "departure_date=" + departure_date + "&limit=10", true);
xmlhttp.send();
}

function listResults(json) {

var results = JSON.parse(json);
console.log(results); // testing
var text = ""; // testing

// filter results for only passenger trains
var passengerTrains = [];
function getPassengerTrains() {
for (var i = 0; i < results.length; i++) {
if (results[i].trainCategory == "Long-distance" || results[i].trainCategory == "Commuter") {
passengerTrains.push(results[i]);
text = text + results[i].trainNumber + "<br>"; // testing
}
}
}
getPassengerTrains();
console.log(passengerTrains); // testing

// Get the desired properties from the filtered trains
// https://stackoverflow.com/questions/37750309/find-object-by-property-in-an-array-of-javascript-objects-inside-another-array

var station = passengerTrains.map(item => item.timeTableRows.stationShortCode);
console.log(station); // but this returns an array full of undefined

// Loop through array of train objects
for (var i = 0; i < passengerTrains.length; i++) {
console.log(passengerTrains[i]); // this seems to give the right result
// Loop through each train object to get timeTableRows subarray
for (var train in passengerTrains[i]) {
// make a new array named timetable
var timetable = passengerTrains[i].timeTableRows;
console.log(timetable);
// but this prints the same array 13 times = as many times as there are properties in the train object
/* Commented out because it freezes my browser
// Loop through each object in the timetable subarray to get the desired properties
for (var j=0; j < timetable.length; j++) {
console.log(timetable[j]);
for (var row in timetable[j]) {
text = text + "<p>From/to: " + timetable[j].stationShortCode;
text = text + "<br>Time: " + timetable[j].scheduledTime;
text = text + "<br>Train stopping: " + timetable[j].trainStopping;
text = text + "<br>Departure/arrival: " + timetable[j].type + "</p>";
}
} */
}
document.getElementById("onscreen_text").innerHTML = text;
}
}

</script>
</body>
</html>

我对编程相当陌生,这是我的第一个问题。我一直在试图弄清楚如何到达 JavaScript 中多层嵌套数组/对象事物的底层。

我正在处理的是一个经过解析的 JSON 文件,其中包含此公共(public) API 返回的类型的火车时刻表: https://rata.digitraffic.fi/api/v1/live-trains/station/HKI/TPE?departure_date=2019-02-12

解析的结果是一个火车对象数组,其中有一个名为 timeTableRows 的子数组,其中充满了具有 stationShortCode: "HKI"、scheduledTime: "2019-02-12T05:04:00.000Z"等属性的对象。我想获取这些底层属性。 Screenshot from console for clarity

我尝试了这里给出的答案: Find object by property in an array of JavaScript objects inside another array

但我不知道如何让它为我工作,因为我不需要找到某个索引,而只需要找到某个名称的属性,而我的尝试只返回“未定义”。我对 ES5 一点也不熟悉,所以我希望能提供一些适合初学者的示例。

我注释掉了其余的 for 循环,因为它们创建了一个迭代的怪物,卡住了我的浏览器。有什么方法可以到达这种结构的底层,而无需多次循环遍历所有内容?

js snippet removed

最佳答案

function fetchNestedObject(prop, obj) {
let keys = prop.split('.');
keys[0] = obj[keys[0]];
return keys.reduce((a, b) => a && a[b]);
}

用法:

fetchNestedObject('v.a.d.0', {v: {a: {d: [1]}}})

关于javascript - 如何从 JavaScript 中的另一个对象数组中的对象数组获取底层属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633488/

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