javascript - 在 JSON 数组中获取最大值
问题描述
我正在尝试编写一个函数,该函数在 JSON 数组中找到最大值,然后从找到最大值的数组中返回另一个值。具体来说:找到具有最高(即最近)创建时间的表,然后返回该表的 id。该函数应返回“clickup-test-example:ClickUp_Teams.ClickUp_Teams_1619170399502”
{
"totalItems": 3,
"kind": "bigquery#tableList",
"etag": "PCARXzLSMg+ycECbmPnMDQ==",
"tables": [
{
"kind": "bigquery#table",
"id": "clickup-test-example:ClickUp_Teams.ClickUp_Teams_1618403016322",
"tableReference": {
"projectId": "clickup-test-example",
"datasetId": "ClickUp_Teams",
"tableId": "ClickUp_Teams_1618403016322"
},
"type": "TABLE",
"creationTime": "1618403016433",
"expirationTime": "1623587016433"
},
{
"kind": "bigquery#table",
"id": "clickup-test-example:ClickUp_Teams.ClickUp_Teams_1619168558388",
"tableReference": {
"projectId": "clickup-test-example",
"datasetId": "ClickUp_Teams",
"tableId": "ClickUp_Teams_1619168558388"
},
"type": "TABLE",
"creationTime": "1619168558487",
"expirationTime": "1624352558487"
},
{
"kind": "bigquery#table",
"id": "clickup-test-example:ClickUp_Teams.ClickUp_Teams_1619170399502",
"tableReference": {
"projectId": "clickup-test-example",
"datasetId": "ClickUp_Teams",
"tableId": "ClickUp_Teams_1619170399502"
},
"type": "TABLE",
"creationTime": "1619170399591",
"expirationTime": "1624354399591"
}
]
}
我尝试基于这两个线程编写此函数: Getting max value(s) in JSON array 和 Finding the max value of an attribute in an array of objects,但我不知道如何编写 Math.max 函数。任何其他解决方案也将不胜感激。提前致谢!
function findNewestTables() {
const tables = BigQuery.Tables.list('clickup-test-307314','ClickUp_Teams'); // returns the JSON file above
const newestTables = Math.max(tables.tables.map(function(o) {
return o.id;
}));
console.log(tables);
console.log(newestTables);
};
解决方案
您可以在单独的变量中跟踪maxSoFar
和,以及何时更改,.id
maxSoFar
id
// Gets the original JSON, and declares the variables
const data = getData();
let
maxSoFar = 0,
id = "";
// Updates the variables whenever a newer item is found
data.tables.forEach(table => {
const time = parseInt(table.creationTime);
if(time > maxSoFar){
maxSoFar = time;
id = table.id;
}
});
// Logs the result
console.log(id);
// Provides the original JSON
function getData(){
return {
"tables": [
{ "id": "Teams_1618403016322", "creationTime": "1618403016433" },
{ "id": "Teams_1619168558388", "creationTime": "1619168558487" },
{ "id": "Teams_1619170399502", "creationTime": "1619170399591" }
]
}
}
推荐阅读
- php - 当 PHP “声明”一堆 HTML / PHP 标签时,这意味着什么?
- android - 自定义 View 有没有办法检测其 Activity 何时暂停或停止?
- asp.net-core - ASP.NET Core 2.2 主布局模型问题
- python - 加入列表中的许多数据在数组中不起作用 python
- html - 粘性导航显示在叠加层上方
- powershell - 在 Excel 公式中包含正斜杠
- android - 谷歌智能锁在一个应用程序中显示我所有的手机账户,而不是以前使用的那些
- python - pip install PDAL 失败,缺少 pdal-config
- windows - 从跳转返回主
- python - 如何加入两个数据框并保留每个数据框的某些列?