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