如何在json数组中获取等于X的最后一个值

时间:2019-01-17 04:05:57

标签: arrays json api

在下面给出的以下响应中(例如,在“估计”之前的那一个),我需要获取最后一个“观察到的”等于“观察到的”的“ num”值。

返回值每三个小时将下一个“估计”更新为“已观察”,并且每次需要API时,我都需要显示更新的“ num”值。

非常感谢您的帮助。

axios.get('http://url_to_api')
  .then(function (response) => {
   //do the magic here to get last observed val
    console.log(LAST_OBSERVED_VAL)
  })

响应:

[  
  [  
    "time_tag",
    "num",
    "observed",
    "scale"
  ],
  [  
    "2019-01-16 18:00:00",
    "2",
    "observed",
    null
  ],
  [  
    "2019-01-16 21:00:00",
    "3",
    "observed",
    null
  ],
  [  
    "2019-01-17 00:00:00",
    "3",  // <-- Get this value
    "observed",
    null
  ],
  [  
    "2019-01-17 03:00:00",
    "2",
    "estimated",
    null
  ],
  [  
    "2019-01-17 06:00:00",
    "2",
    "estimated",
    null
  ],
  [  
    "2019-01-18 00:00:00",
    "2",
    "predicted",
    null
  ],
  [  
    "2019-01-18 03:00:00",
    "1",
    "predicted",
    null
  ],
]

1 个答案:

答案 0 :(得分:1)

您可以插入类似以下内容:

var k, LAST_OBSERVED_VAL = '';
for (k = response.data.length-1; k >= 0; k--)
{
    if (response.data[k][2] == "observed")
    {
        LAST_OBSERVED_VAL = response.data[k][1];
        break;
    }
}