ikemonn's blog

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

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

jashkenas/underscore_.whereを読んだ。

概要

_.where(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 = _.where(list, {age: 20, country: "JP"});
console.log(x); // [{age: 20, sex: "male", country: "JP", name: "hoge"},{age: 20, sex: "female", country: "JP", name: "HOGE"}]

ソースコード

 _.where = function(obj, attrs) {
    return _.filter(obj, _.matcher(attrs));
  };

_.matcher = _.matches = function(attrs) {
    attrs = _.extendOwn({}, attrs);
    return function(obj) {
      return _.isMatch(obj, attrs);
    };
  };

_.isMatch = function(object, attrs) {
    var keys = _.keys(attrs), length = keys.length;
    if (object == null) return !length;
    var obj = Object(object);
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      if (attrs[key] !== obj[key] || !(key in obj)) return false;
    }
    return true;
  };

_.isMatchの 

if (attrs[key] !== obj[key] || !(key in obj)) return false;

にある、 !(key in obj)) は、attrsにしかないプロパティの値がundefinedの時に、結果がtrueになってしまうのを防ぐ。

var obj = {
    sex :  “male",
    age : 20
};
var obj2 = {
    sex :  “male",
       name : undefined
};
var x = _.isMatch( obj, obj2); // x = false

参考

jashkenas/underscore