Using jQuery's grep to parse JSON data

Quick intro into Jquery's powerful grep() API

Using jQuery's grep to parse JSON data

jQuery’s grep() is a powerful and underutilised filter method. It’s a simple method which helps in searching/filtering data in arrays. Grep() is quite helpful when we have to parse JSON data. It’s return type is an array.

https://api.jquery.com/jQuery.grep/

Description: Finds the elements of an array which satisfy a filter function. The original array is not affected.

To extract all employee ids

var sampleArray = '1,EmpNameA,2,EmpNameB,3,EmpNameC,4,EmpNameD'.split(',');
var OutputArray = $.grep(sampleArray, function(objItem, index) {
    // Check if objItem passed is a number (isNAN), 
    // return TRUE if objItem is a number else FALSE
    return !isNaN(objItem);
});

Another example is on how to use grep() on JSON. Suppose we need to extract only active employees from a JSON, we can filter the same using grep() and look for Active = True

var SampleJSON = [{
    "EmpId": 1,
    "EmpName": "EmployeeA",
    "Active": "True"
}, {
    "EmpId": 2,
    "EmpName": "EmployeeB",
    "Active": "False"
}, {
    "EmpId": 3,
    "EmpName": "EmployeeC",
    "Active": "True"
}, {
    "EmpId": 4,
    "EmpName": "EmployeeD",
    "Active": "False"
}, {
    "EmpId": 5,
    "EmpName": "EmployeeE",
    "Active": "True"
}, {
    "EmpId": 6,
    "EmpName": "EmployeeF",
    "Active": "False"
}, {
    "EmpId": 7,
    "EmpName": "EmployeeG",
    "Active": "False"
}, {
    "EmpId": 8,
    "EmpName": "EmployeeH",
    "Active": "True"
}];

var OutputArray = $.grep(SampleJSON, function(objItem) {
    return objItem.Active == True;
});