过滤对象数组
filter()
方法接受测试函数,并返回一个新数组,该数组仅包含通过所提供测试的原始数组的元素。
// Suppose we want to get all odd number in an array:
var numbers = [5, 32, 43, 4];
Version >= 5.1
var odd = numbers.filter(function(n) {
return n % 2 !== 0;
});
Version >= 6
let odd = numbers.filter(n => n % 2 !== 0); // can be shortened to (n => n % 2)
odd
将包含以下数组:[5, 43]
。
它也适用于一组对象:
var people = [{
id: 1,
name: "John",
age: 28
}, {
id: 2,
name: "Jane",
age: 31
}, {
id: 3,
name: "Peter",
age: 55
}];
Version >= 5.1
var young = people.filter(function(person) {
return person.age < 35;
});
Version >= 6
let young = people.filter(person => person.age < 35);
young
将包含以下数组:
[{
id: 1,
name: "John",
age: 28
}, {
id: 2,
name: "Jane",
age: 31
}]
你可以在整个数组中搜索如下值:
var young = people.filter((obj) => {
var flag = false;
Object.values(obj).forEach((val) => {
if(String(val).indexOf("J") > -1) {
flag = true;
return;
}
});
if(flag) return obj;
});
返回:
[{
id: 1,
name: "John",
age: 28
},{
id: 2,
name: "Jane",
age: 31
}]