ES6中的数组⽅法(filter)假定有⼀个对象数组,获取数组中指定类型的对象数组放到B数组中
var arr = [
{name:'jerry',sex:'man'},
{name:'jack',sex:'woman'}
]
var manArr = arr.filter(function(obj){
return obj.sex === "man"; //获取性别为man的对象
})filter过滤对象数组
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:'赵六'}]
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论