gpt4 book ai didi

Javascript 从 JSON 数组中提取特定记录

转载 作者:行者123 更新时间:2023-11-30 10:09:50 25 4
gpt4 key购买 nike

我有一个像这样的 JSON 数组:

[{"Name":"Bob", "EmployeeID":1234, "StartDate":"12/01/2011"},
{"Name":"Jim", "EmployeeID":4432, "StartDate":"01/12/1997"},
{"Name":"Heather", "EmployeeID":6643, "StartDate":"07/09/2010"}]

我如何使用 Javascript 通过 EmployeeID (4432) 搜索查找和检索 Jim 的记录?

最佳答案

您可以使用过滤器:

var records = [{"Name":"Bob", "EmployeeID":1234, "StartDate":"12/01/2011"},
{"Name":"Jim", "EmployeeID":4432, "StartDate":"01/12/1997"},
{"Name":"Heather", "EmployeeID":6643, "StartDate":"07/09/2010"}];

var result = records.filter(function(r) { return r["EmployeeID"] == 4432 })[0]||'No record found';

搜索功能可以实现如下:

function findByEmployeeId(records, employeeId) {
return records.filter(function(r) { return r["EmployeeID"] == employeeId })[0]||null;
}

一般来说,如果您对数据有任何控制权,我会建议更改结构以使您的生活更轻松。如果使用以下结构,则可以使用 records[employeeId] 直接访问记录:

{ "1234" : {"Name":"Bob", "EmployeeID":1234, "StartDate":"12/01/2011"},
"4432" : {"Name":"Jim", "EmployeeID":4432, "StartDate":"01/12/1997"},
"6643" : {"Name":"Heather", "EmployeeID":6643, "StartDate":"07/09/2010"} }

关于Javascript 从 JSON 数组中提取特定记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27114097/

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