首页 > 解决方案 > 在 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 arrayFinding 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);

};

标签: javascriptnode.jsjson

解决方案


您可以在单独的变量中跟踪maxSoFar和,以及何时更改,.idmaxSoFarid

// 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" }
    ]
  }
}


推荐阅读