简体   繁体   English

从对象数组中获取索引

[英]getting an index from an array of objects

I am using the openweather api for a project and the data fluctuates based on what time of day you view it.我正在为一个项目使用 openweather api,数据会根据您查看它的时间而波动。 So, I am trying to loop through the first 8 objects to find a dt_txt = to 12:00:00.所以,我试图遍历前 8 个对象以找到 dt_txt = 到 12:00:00。 I need to assign the result to a var so I can then increment that by 8.我需要将结果分配给一个 var,这样我就可以将其增加 8。

here is how the data comes (first index only):这是数据的来源(仅限第一个索引):

0:
dt: 1579316400
main: {temp: 271.29, feels_like: 259.49, temp_min: 271.29, temp_max: 272.35, pressure: 1026, …}
weather: [{…}]
clouds: {all: 100}
wind: {speed: 13.55, deg: 147}
snow: {3h: 5}
sys: {pod: "n"}
dt_txt: "2020-01-18 03:00:00"
__proto__: Object 

my attempt:我的尝试:

for (let i = 0; i < 8; i++) {
  if ((response.list[i].dt_txt).substring(11) === "12:00:00") {
    var noon = indexOf("12:00:00")
    console.log(noon);

Thanks in advance!提前致谢!

Edit I thought I was missing something obvious!编辑我以为我错过了一些明显的东西!

Working code:工作代码:

for (let i = 0; i < 8; i++) {
                if ((response.list[i].dt_txt).substring(11) === "12:00:00") {
                    var noon = response.list[i]
                    console.log(noon);
                    var noon2 = response.list[i + 8]
                    console.log(noon2);

Have a read on Javascript Array methods ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter )阅读 Javascript 数组方法 ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter )

eg filter will return the object from the list that meets your criteria.例如,过滤器将从符合您条件的列表中返回对象。 const result = response.list.filter(res => res.dt_txt === "12:00");

or findIndex will return the index of the search.或 findIndex 将返回搜索的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM