gpt4 book ai didi

javascript - 从数组中检索值的更简单方法

转载 作者:行者123 更新时间:2023-11-28 14:24:15 25 4
gpt4 key购买 nike

是否有更简单的方法来检索 JSON 响应中的值 "TestProject" 而不是在代码中使用 for 循环?

[
{
"Id": "9ac44c1d-0066-47aa-a2a2-a9b90109b0a5",
"Group": null,
"DataFields": [
{
"Header": "ProjectID",
"Value": "TestProject"
},
{
"Header": "uui_ConfigPack",
"Value": "75e8ce5a-7ae0-41ca-86f0-aca1e7158073"
}
],
"HasDocuments": null
}
]
var projResults = JSON.parse(responseBody);

var projNumber = 1;

dataProjectId = projResults[projNumber].Id;

projName = 'Not Found';
for (i = 0; i < projResults[projNumber].DataFields.length; i++)
{
if(projResults[projNumber].DataFields[i].Header == "ProjectID")
{
projName = projResults[projNumber].DataFields[i].Value;
}
}

最佳答案

看起来您正在尝试在数组中查找一个对象,最常用的方法是Array.prototype.find:

var projResults = [
{
"Id": "9ac44c1d-0066-47aa-a2a2-a9b90109b0a5",
"Group": null,
"DataFields": [
{
"Header": "ProjectID",
"Value": "TestProject"
},
{
"Header": "uui_ConfigPack",
"Value": "75e8ce5a-7ae0-41ca-86f0-aca1e7158073"
}
],
"HasDocuments": null
}
];
var projNumber = 0;
const foundObj = projResults[projNumber].DataFields.find(({ Header }) => Header === 'ProjectID');
const projName = foundObj ? foundObj.Value : 'Not Found';
console.log(projName);

关于javascript - 从数组中检索值的更简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54146228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com