最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use _.where method from underscore.js library for more elaborated searchs - Stack Overflow

programmeradmin4浏览0评论
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 []

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]

where object is the reference for c[1];

EDIT: 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
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 []

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]

where object is the reference for c[1];

EDIT: 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
Share Improve this question edited Jan 2, 2014 at 18:00 Colin Brock 21.6k9 gold badges49 silver badges62 bronze badges asked Jan 2, 2014 at 17:45 Lothre1Lothre1 3,8539 gold badges49 silver badges66 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 12

_.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 mon 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 ment in the source is clear.

发布评论

评论列表(0)

  1. 暂无评论