假定有一个对象数组, 获取数组中指定类型的对象数组放到新数组中
var arr = [
{name:'jerry',sex:'man'},
{name:'jack',sex:'woman'}
]
var manArr = arr.filter(function(obj){
return obj.sex === "man"; //获取性别为man的对象
})
console.log(manArr); //[{name: "jerry", sex: "man"}]
假定有一个对象数组, 过滤掉不满足条件的对象
var arr = [
{name:'jerry',sex:'man',age:22},
{name:'jack',sex:'woman',age:19},
{name:'liming',sex:'man',age:17}
]
var childBoyArr = arr.filter(function (obj) {
return obj.sex === 'man' && obj.age < 18; //获取小于18岁的男孩
})
console.log(childBoyArr); //[{name: "liming", sex: "man", age: 17}]
假定有两个数组,根据第一个数组的值过滤另一个数组不符合的数据
var arr1 = [{id:2}]
var arr2 = [
{pId:3,name:'张三'},
{pId:2,name:'李四'},
{pId:4,name:'王五'},
{pId:2,name:'赵六'}
]
var newArr = arr2.filter(function(obj){
return obj.pId == arr1[0].id;
})
console.log(newArr); //[{pId:2,name:'李四'},{pId:2,name:'赵六'}]