lodash while filtering ignore few values

时间:2016-08-31 17:35:35

标签: javascript filter lodash

I am using lodash's filter function to filter an array. The array has some objects with disabled set to true that need to be shown all the time. I also want all objects in the array that has a value of v that is present in obj.

var obj = ["98100","99100"];

var mainObj = [
  {"v":"99999","d":"United States (National)","disabled":false},
  {"v":"98999","d":"Census Regions and Divisions","disabled":true},
  {"v":"98100","d":"Northeast Region","disabled":false},
  {"v":"99100","d":"New England Census Division","disabled":false},
  {"v":"99120","d":"Middle Atlantic Census Division","disabled":false},
  {"v":"98200","d":"South Region","disabled":false},
  {"v":"99140","d":"South Atlantic Census Division","disabled":false},
  {"v":"99130","d":"East South Central Census Division","disabled":false},
  {"v":"99170","d":"West South Central Census Division","disabled":false}
];

How do I get those values?

My code:

var arr = _.filter(mainObj, function(item) {
  for (var i = 0; i < obj.length; i++) {
    if (item.v === obj[i]) {
      return true;                                      
    }
  } 
});

1 个答案:

答案 0 :(得分:0)

要返回数组中v中存在值obj的每个对象,并返回每个禁用的对象,您可以使用此谓词:

var result = _.filter(mainObj, function(el) {
  return el.disabled === true || obj.indexOf(el.v) !== -1;
});

&#13;
&#13;
var obj = ["98100","99100"];
var mainObj = [
  {"v":"99999","d":"United States (National)","disabled":false},
  {"v":"98999","d":"Census Regions and Divisions","disabled":true},
  {"v":"98100","d":"Northeast Region","disabled":false},
  {"v":"99100","d":"New England Census Division","disabled":false},
  {"v":"99120","d":"Middle Atlantic Census Division","disabled":false},
  {"v":"98200","d":"South Region","disabled":false},
  {"v":"99140","d":"South Atlantic Census Division","disabled":false},
  {"v":"99130","d":"East South Central Census Division","disabled":false},
  {"v":"99170","d":"West South Central Census Division","disabled":false}
];

var result = _.filter(mainObj, function(el) {
  return el.disabled === true || obj.indexOf(el.v) !== -1;
});

console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
&#13;
&#13;
&#13;