[英]How can I access the highest value of a nested element in a JSON data set using Javascript
I know there's a simple way to do this but I'm struggling to find it.我知道有一种简单的方法可以做到这一点,但我很难找到它。 Not sure if JSON.parse() or findIndex() or something else would be best.不确定 JSON.parse() 或 findIndex() 或其他东西是否最好。 ultimately I need to get the highest number value of the "Number" element and concatenate that with 2 other variables to make a 12 digit Unique ID.最终,我需要获取“数字”元素的最高数值并将其与其他 2 个变量连接起来以生成 12 位唯一 ID。 There could be 100 "Number" values.可能有 100 个“数字”值。 These are incremented based on application saves and I want to get the latest save which will be represented by the highest "Number" value.这些是根据应用程序保存递增的,我想获得最新的保存,它将由最高的“数字”值表示。 This example just has 2. The structure of the JSON text is as follows:这个例子只有2个。JSON文本的结构如下:
{
"History": [
{
"Id": "244725",
"Number": "1",
"CreateDate": "2022-07-13 11:08:17.073",
"AppStatus": "App Status",
"DataElements": [
{
"Id": "432",
"Name": "App Status",
"Value": "App Status",
"GroupId": "3",
"CustomLabel": null
}
]
},
{
"Id": "244726",
"Number": "2",
"CreateDate": "2022-07-13 11:13:39.743",
"AppStatus": "App Status",
"DataElements": [
{
"Id": "432",
"Name": "App Status",
"Value": "App Status",
"GroupId": "3",
"CustomLabel": null
}
]
}
]
}
I have a function where I want to return the 3 concatenated values as a single 12 character string.我有一个函数,我想将 3 个连接值作为单个 12 个字符的字符串返回。
function main(applicationNumber, historyJson) {
const x = 1;
const appNum = applicatinNumber.substring(1);
const history = JSON.parse(historyJson).History.Number.length - 1;
return applicant += appNum += history;
}
This isn't working but my bigger issue is finding the best way to return the highest logged "Number" value.这不起作用,但我更大的问题是找到返回最高记录“数字”值的最佳方法。
This would require recursion.这将需要递归。 I have used the iterate
function to traverse the entire object.我使用了iterate
函数来遍历整个对象。 Along the way I searched for the maximal Number
.一路上我搜索了最大的Number
。
var data = { "History": [{ "Id": "244725", "Number": "1", "CreateDate": "2022-07-13 11:08:17.073", "AppStatus": "App Status", "DataElements": [{ "Id": "432", "Name": "App Status", "Value": "App Status", "GroupId": "3", "CustomLabel": null }] }, { "Id": "244726", "Number": "2", "CreateDate": "2022-07-13 11:13:39.743", "AppStatus": "App Status", "DataElements": [{ "Id": "432", "Name": "App Status", "Value": "App Status", "GroupId": "3", "CustomLabel": null }] } ] } var max_Number = -Infinity; const iterate = (obj) => { if (!obj) { return; } Object.keys(obj).forEach(key => { // console.log(`key: ${key}, value: ${obj[key]}`) var value = obj[key] if (key == 'Number' && value > max_Number) { max_Number = value } if (typeof obj[key] === "object") { iterate(obj[key]) } }) } iterate(data) console.log(max_Number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.