如何使用underscore.js库中的_.where方法进行更精细的搜索 [英] How to use _.where method from underscore.js library for more elaborated searchs

查看:622
本文介绍了如何使用underscore.js库中的_.where方法进行更精细的搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var a = {
    "title": "Test 1",
    "likes": {
        "id": 1
    }
}

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


var c = [a, b];

var d = _.where(c, {
    "title": "Test 2",
    "likes": {
        "id": 2
    }
});
//d => outputs an empty array []

在这种情况下,我希望在内存中获得对象的引用但是d
但实际上它只适用于root属性。

In this situation i would expect to get the reference to object in memory but d but actually it just works on root properties.

_.where(c, {title: "Test 2"});
=> outputs [object]

其中object是c [1]的引用;

where object is the reference for c[1];

编辑:
使用_.filter()

found a possible solution using _.filter()

_.filter( c, function(item){ 
    if (item.title == "Test 1" && item.likes.id == 1){
        return item;
    } 
})

outputs => [object] with reference for variable a


推荐答案

_。filter 是正确的方法, _。其中 只是 _。过滤过滤简单键/值对的快捷方式。您可以从来源中看到这一点:

_.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.

这篇关于如何使用underscore.js库中的_.where方法进行更精细的搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆