使用航班数据API构建网络应用程序,而且,斗争是真实的。
我返回的数组和它的对象看起来像这样:
results:
0:{destination: "YTO",
departure_date: "2018-01-24",
return_date: "2018-01-25"
airline: "TS"}
1:{destination: "BOS",
departure_date: "2018-01-08",
return_date: "2018-01-11",
airline: "AC"}
2:{destination: "SJU",
departure_date: "2018-01-31",
return_date: "2018-02-01",
airline: "AA"}
在我将结果转储到DOM中以显示给站点的访问者之前,我需要通过额外的API(长篇故事)运行某些返回值,所以我显然需要以某种方式隔离它们。
对于这个例子,我正在使用目的地,所以我的初始思考过程首先要注销:
console.log(response.results[0].destination);
我们知道将在FIRST对象中打印FIRST目的地,因为[0]是该对象的索引(因此在这种情况下,我们返回YTO)。
由于每个返回的对象都有一个索引号,我想我需要循环遍历它们(对于每个?)来提取我需要的值,但我正在尝试不带运气的变化.....或者所有我知道这完全是另一回事。
(你的两分钱在这里)
答案 0 :(得分:1)
forEach适用于数组。 尝试使用for循环
> dput(dat[1:20])
structure(list(tme = structure(c(1512489600, 1512493200, 1512496800,
1512500400, 1512504000, 1512507600, 1512511200, 1512514800, 1512518400,
1512522000, 1512525600, 1512529200, 1512532800, 1512536400, 1512540000,
1512543600, 1512547200, 1512550800, 1512554400, 1512558000), class = c("POSIXct",
"POSIXt"), tzone = "America/Chicago"), degc = c(24, 21, 21, 19,
18, 17, 16, 15, 14, 14, 13, 12, 12, 12, 11, 11, 10, 10, 9, 9),
rh = c(89, 87, 88, 82, 81, 79, 76, 80, 80, 80, 78, 75, 71,
68, 67, 68, 71, 76, 78, 80), type = c("forecast_1", "forecast_1",
"forecast_1", "forecast_1", "forecast_1", "forecast_1", "forecast_1",
"forecast_1", "forecast_1", "forecast_1", "forecast_1", "forecast_1",
"forecast_1", "forecast_1", "forecast_1", "forecast_1", "forecast_1",
"forecast_1", "forecast_1", "forecast_1"), pres = c(NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_), prec = c(NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_, NA_real_, NA_real_)), .Names = c("tme",
"degc", "rh", "type", "pres", "prec"), class = c("data.table",
"data.frame"), row.names = c(NA, -20L), .internal.selfref = <pointer: 0x00000000000b0788>)
答案 1 :(得分:1)
您可以使用Object
方法将Object.keys()
的键转换为数组,这样您就可以使用Array.forEach()
方法遍历Object的可枚举属性,就像这样...
Object.keys(dataObj).forEach(function(k) {
var dest = dataObj[k].destination;
/* ... etc ... */
});
希望有所帮助。
Object.keys()
@MDN