ikemonn's blog

技術ネタをちょこちょこと

【Underscore.js】_.findWhereを読んだ

jashkenas/underscore_.findWhereを読んだ。

概要

_.findWhere(list, properties) 

propertiesの中にあるkey-valueが含まれるもの中で、listの中の一番最初のものを取得する。

var list = [
    {age: 20, sex: "male", country: "JP", name: "hoge"},
    {age: 22, sex: "male", country: "US", name: "fuga"},
    {age: 20, sex: "female", country: "US", name: "piyo"},
    {age: 45, sex: "male", country: "JP", name: "HUGA"},
    {age: 20, sex: "female", country: "JP", name: "HOGE"}
];
var x = _.findWhere(list, {age: 20, country: "JP"});
console.log(x); // {age: 20, sex: "male", country: "JP", name: "hoge"}

ソースコード

_.findWhere = function(obj, attrs) {
    return _.find(obj, _.matcher(attrs));
  };

.matcherが、key-valueが含まれるかどうかをbooleanで返す部分適用された関数を返す。 .matcherと.findが組み合わさって、.findWhereができており、自分もこのくらい小さい機能の関数を作ってうまく組み合わせられるようになりたいと思った。

参考

jashkenas/underscore