Get an object from array which contains a specific value

前端 未结 2 922
南方客
南方客 2020-12-14 15:14

I am trying to search through an array of objects using Underscore.js, but I can\'t seem to target the one I want.

console.log(_.findWhere(response.data, { T         


        
2条回答
  •  不知归路
    2020-12-14 15:54

    The source of _.findWhere / _.where is as follows

    _.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;
      });
    };
    
    _.findWhere = function(obj, attrs) {
      return _.where(obj, attrs, true);
    };
    

    As you can see, it performs strict equality rather than deep equality. If you want a deep searching where, this would suffice (untested, unoptimized):

    _.whereDeep = 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] || !(_.isObject(attrs[key]) && _.whereDeep([value[key]], attrs[key], true))) return false;
        }
        return true;
      });
    };
    
    _.findWhereDeep = function(obj, attrs) {
      return _.whereDeep(obj, attrs, true);
    };
    

    And you would be able to use your code, almost unchanged

    _.findWhereDeep(response.data, { TaskCategory: { TaskCategoryId: $routeParams.TaskCategory } });
    

提交回复
热议问题