Help us understand the problem. What is going on with this article?

[JavaScript] オブジェクトの配列に対してフィルタリングしてみる

More than 1 year has passed since last update.

filterメソッドを使えばよい。

let users = [
  {
    name: "Taroimo",
    age: 27
  },
  {
    name: "Hanako",
    age: 18
  },
  {
    name: "Sabuibo",
    age: 36
  }
];

結果は配列で返って来る。

let users1 = users.filter(function(item, index) {
  if (item.age >= 20) return true;
});
console.log(users1);
[ { name: "Taroimo", age: 27 }, { name: "Sabuibo", age: 36, } ]

抽出結果が1件でも配列で返って来る。

let users1 = users.filter(function(item, index) {
  if ((item.name).indexOf("imo") >= 0) return true;
});
console.log(users2);
[ { name: "Taroimo", age: 27 } ]

該当なしの場合も空の配列で返って来る。

let users3 = users.filter(function(item, index) {
  if (item.age >= 65) return true;
});
console.log(users3);
[]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away