简体   繁体   中英

Filtering results of JSON Object

var employees = {
"staff": [
  {"name": "Bob", "gender": "Male"},
  {"name": "Sue", "gender": "Female"},
  {"name": "Eric", "gender": "Male"},
  {"name": "Jo", "gender": "Female"}    
  ]
}

After iterating through this json structure, is there a method to selectively delete an entire row based on the gender selection? Ideally I'd like to have a new object but without any Males, for example.

There's the .filter() function:

employees.staff = employees.staff.filter(function(e) { return e.gender !== "Male"; });

The .filter() method is available for arrays in newer versions of JavaScript (modern browsers). For older browsers, there is a polyfill available .

use $.grep() - Array.filter() is not used because of IE < 9 support

var females = $.grep(employees.staff, function (obj) {
    console.log(this, arguments)
    return obj.gender == "Female"
})
console.log(females)

Another solution is to use Array.filter() with the pollyfill

employees.staff = filter(employees.staff, "Female");

function filter(data, filter) {
    return data.filter(function(row) {
        return row.gender === filter;
    });
}

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