Saturday 15 March 2014

underscore.js - lodash Filter collection using array of values -


I want to filter an archive using the array of property values. Returning the objects with the matching ID, looking at an array of IDs There is no shortcut method using lodash / underscore

  var collection = [{id : 1, name: 'xyz'}, {id: 2, name: 'ds'}, {id: 3, name: 'rtrt'}, {id: 4, name: 'nhf'}, {id: 5 , Name: 'qwe'}]; Var Ieds = [1,3,4]; // it works, but is there any better way? Var filtered = _.select (collection, function (c) {returns ids.indexOf (c.id)! = -1});    

If you are going to use a lot of this kind of pattern, you create It may be like a mixine, however, it is not separating anything from your original code. It just makes it more developer.

  _ mixin ({'findByValues': function (collection, property, value) {return _.filter (collection, function (item) {return_ contains (value, item [ Property]);});}});   

Then you can use it this way.

  var collection = [{id: 1, name: 'xyz'}, {id: 2, name: 'd'}, {id: 3, name: 'rtrt'} , {Id: 4, name: 'nhf'}, {id: 5, name: 'qwe'}]; Var filtered = _.findbuildels (collection, "id", [1,3,4]);   

Update - This answer is outdated and is Clanky. Please use for a much more elegant solution. _ (archive) .keyBy ('id') // or .indexBy () if using Londas 3.x .at (id) value ();

No comments:

Post a Comment