LoginSignup
0
0

More than 1 year has passed since last update.

find

Last updated at Posted at 2021-07-03

findメソッド

findメソッドについて

構文

配列.find(function(引数[, index[, array]]){
   処理内容
});

基礎

var users = [
  {name:  'Rei' },
  {name:  'Yohji' },
  {name:  'Issei' },
  {name:  'Kenzo' },  
];

var user;

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

//結果 
// {"name":'Rei'}


findを使用してコメントに紐づくポストを探す

var posts = [
  {id: 1, title: 'old post'},
  {id: 2, title: 'new post'}
];

var comment = { postId:2, content: 'Liked' };

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

console.log(postForComment(posts, comment));

//結果  {"id":2,"title":"new post"}
function postForComment(posts, comment) {//関 コメントに紐づくpostを探す (postS,comment)
  return posts.find(function(post) { //何がしたいかというと、特定のpostを探す(post)
    return post.id === comment.postId; // ポストのidとコメントのpostidが一致しているものを探すよ
  });
}

console.log(postForComment(posts, comment));

findの使い所

ページ詳細画面に飛ぶ際など。

練習

管理者ユーザー情報のみ引き出す


var users = [
  { id: 1, admin: false },
  { id: 2, admin: false },
  { id: 3, admin: true }
];

var admin = users.find(function(user){
    return user.admin === true;
});

findWhere

コールバック関数いらずになる。

function findWhere(array, criteria){
  return array.find(function(element) {
    var property = Object.keys(criteria)[0];    
    return element[property] === criteria[property];
  });
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0