Adam
Adam

Reputation: 609

Javascript to Pull Specific Record from JSON Array

I have a JSON array like this:

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

How can I use Javascript to find and retrieve the record for Jim, searching by EmployeeID (4432)?

Upvotes: 1

Views: 2444

Answers (2)

Matthew Sant
Matthew Sant

Reputation: 1631

You can use 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';

A search function could be implemented as follows:

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

In general, if you have any control over the data, I would recommend changing the structure to make your life easier. If you use the following structure you can access the record directly by using 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"} }

Upvotes: 6

fictus
fictus

Reputation: 286

First of all, Your JSON object is incorrect; it's missing two commas. It should be:

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

So, you can access EmplyeeID 4432 like this:

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);
}

Upvotes: -1

Related Questions