1

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)?

2 Answers 2

6

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"} }
Sign up to request clarification or add additional context in comments.

6 Comments

or find() if you can to use ECMAScript 6 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
When I try your function example, the console says "records.filter is not a function..."
Not every browser has this yet, but I'd recommend checking out Underscore.js that gives you a lot of search functionality.
Unfortunately I don't have control over the data... this is being sent as a feed from a different server
@Adam this would occur if records is not an array, or if you're using IE 8 or lower. If the former, pass an array for records. If the latter, try the polyfill at MDN.
|
-1

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

1 Comment

OP wants to retrieve the employee by its EmployeeID – this retrieves it by its array index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.