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

时间:2014-11-24 21:01:34

标签: javascript json

我有一个像这样的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查找和检索Jim的记录,按EmployeeID(4432)搜索?

2 个答案:

答案 0 :(得分:5)

您可以使用filter

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

答案 1 :(得分:-1)

首先,您的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"}]

因此,您可以像这样访问EmplyeeID 4432:

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

function showJSON() {
  alert(myJSONobject[1].EmployeeID);
}