gpt4 book ai didi

javascript - 如何使用 javascript 从 JSON 访问单个对象?

转载 作者:行者123 更新时间:2023-11-28 19:18:43 25 4
gpt4 key购买 nike

我有一个 JSON 列表,该列表来自具有多个同级的数据库中的表。

"PlayerNumbers":{"PlayerNumber":[
{"Section":"1","Team":"1","Direction":"N","Number":"00280149","Name":" ANSART A","Updated":"False","TimeLog":"","Processed":"False"},
{"Section":"1","Team":"1","Direction":"S","Number":"00280131","Name":"ANSART Y","Updated":"False","TimeLog":"","Processed":"False"},
{"Section":"1","Team":"2","Direction":"N","Number":"01964990","Name":" LAHAYE B","Updated":"False","TimeLog":"","Processed":"False"}]}

假设我需要读取“名称”键,其中部分 = 1,团队 = 2,方向 = N。

编辑:当然我会使用 js 解析对象

Javascript 的语法是什么?

最佳答案

我假设您根本不处理 JSON,而是处理从 JSON 解析的对象树。我假设您给出的是对象定义的内容,如以下 JSON:

{
"PlayerNumbers": {
"PlayerNumber": [
{
"Section": "1",
"Team": "1",
"Direction": "N",
"Number": "00280149",
"Name": " ANSART A",
"Updated": "False",
"TimeLog": "",
"Processed": "False"
},
{
"Section": "1",
"Team": "1",
"Direction": "S",
"Number": "00280131",
"Name": "ANSART Y",
"Updated": "False",
"TimeLog": "",
"Processed": "False"
},
{
"Section": "1",
"Team": "2",
"Direction": "N",
"Number": "01964990",
"Name": " LAHAYE B",
"Updated": "False",
"TimeLog": "",
"Processed": "False"
}
]
}
}

因此,解析 JSON 后,您将获得一个具有 PlayerNumbers 属性的对象,该对象引用具有 PlayerNumber 属性的对象,该属性引用一个数组包含您想要的信息的对象。

因此,您循环遍历数组,直到找到第一个匹配的条目(假设您只需要第一个):

var name;
obj.PlayerNumbers.PlayerNumber.some(function(entry) {
if (entry.Section == "1" && Team == "2" && entry.Direction == "N") {
name = entry.Name;
return true;
}
return false;
});

如果您想要所有匹配项:

var names = obj.PlayerNumbers.PlayerNumber.filter(function(entry) {
return (entry.Section == "1" && Team == "2" && entry.Direction == "N");
}).map(function(entry) { return entry.Name; });
<小时/>

以上两者都使用过时引擎上缺少的 Array 的 ES5 功能。如果您需要支持过时的引擎,以上所有内容都可以“填充”或“填充”,搜索应该会找到必要的填充/填充。

关于javascript - 如何使用 javascript 从 JSON 访问单个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29331757/

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