find

カテゴリー:

findメソッドは特定の要素を探し出す時に利用する。

見つからない場合は、undefindを返す。

filterとは違い、findは一番初めに見つかった要素を返す。

基本的な使い方


上記の例の場合は、最初に見つかった”次郎”しか返さないので、もしもう1人次郎がいたとしても最初の”次郎”しか取得することができない。

応用例

const users = [
  {
    name: '太郎'
  }, {
    name: '次郎'
  }, {
    name: '三郎'
  }
];

users.find(function (user) {
  return user.name === '次郎'
});

複数のコレクションがある場合

function Car(model) {
  this.model = model;
}

const cars = [
  new Car('プリウス'),
  new Car('ノート'),
  new Car('アクア')
]

cars.find(function (car) {
  return car.model === 'アクア'
});

使用シーン

SPAでよく使うメソッド、全投稿から特定のIDのものを取得するなど

const posts = [
  {
  id: 1,
  title: '古い投稿'
  }, {
    id: 2,
    title: '新しい投稿'
  }
];

const comment = {
  postId: 2,
  content: 'いいね!'
};

function postForComment(posts, comment) {
  return posts.find(function (post) {
    return post.id === comment.postId;
  });
}

 

参考URL

タグ: