Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
439 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...