How to use _.where method from underscore.js library for more elaborated searchs

后端 未结 1 1084
谎友^
谎友^ 2020-12-16 20:08
var a = {
    \"title\": \"Test 1\",
    \"likes\": {
        \"id\": 1
    }
}

var b = {
    \"title\": \"Test 2\",
    \"likes\": {
        \"id\": 2
    }
}


va         


        
相关标签:
1条回答
  • 2020-12-16 20:55

    _.filter is the right way to do this, _.where is just a _.filter shortcut for filtering on simple key/value pairs. You can see this from the source:

    // Convenience version of a common use case of `filter`: selecting only objects
    // containing specific `key:value` pairs.
    _.where = function(obj, attrs, first) {
      if (_.isEmpty(attrs)) return first ? void 0 : [];
      return _[first ? 'find' : 'filter'](obj, function(value) {
        for (var key in attrs) {
          if (attrs[key] !== value[key]) return false;
        }
        return true;
      });
    };
    

    The docs could be a little more explicit but at least the comment in the source is clear.

    0 讨论(0)
提交回复
热议问题