简体   繁体   中英

Filter Json Object using Jquery

I am working on Asp.NET (2.0). I have a json response like this.

{
  "0": {
    "EMPLOYEE_CODE": "049",
    "EMPLOYEE_NAME": "Craig J Miller",
    "EMPLOYEE_CITY": "Tustin",
    "EMPLOYEE_STATE": "CA"
  },
  "1": {
    "EMPLOYEE_CODE": "050",
    "EMPLOYEE_NAME": "Stephen B",
    "EMPLOYEE_CITY": "FOLSOM",
    "EMPLOYEE_STATE": "CA"
  },
  "2": {
    "EMPLOYEE_CODE": "051",
    "EMPLOYEE_NAME": "Mithali Raj",
    "EMPLOYEE_CITY": "Glendale",
    "EMPLOYEE_STATE": "AZ"
  },
  "3": {
    "EMPLOYEE_CODE": "052",
    "EMPLOYEE_NAME": "Gordon Green",
    "EMPLOYEE_CITY": "Pheonix",
    "EMPLOYEE_STATE": "AZ"
  }
}

Now i want to filter the above json response by EMPLOYEE_STATE as the search criteria.

I am new to JSON and jQuery.

You may try this

function filter_by_employee_state(query, obj)
{
    var new_obj={}, total=0, query=query.toLowerCase();
    for(var i in obj)
    {
        var emp_st=obj[i].EMPLOYEE_STATE.toLowerCase();
        if(emp_st==query) { new_obj[i]=obj[i]; total++; }
    }
    if(total>0) return new_obj;
    return false;
}

// Filter the data object
var filtered_data=filter_by_employee_state('ca', data);

An Example Here .

When comes down to the browser, if you're using Jquery's get or related methods it'll just become a json object.

If you know that already and just want to filter the array take a look at this: http://linqjs.codeplex.com

Although filtering it on the server maybe preferable depending on your scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM