過濾物件陣列

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
}]