使用查询数组的lodash过滤器数组

时间:2016-08-25 21:42:01

标签: lodash

如何使用lodash过滤下面的对象数组?这是我的查询

var query = { "body": ["Hatchback", "Sedan"] };

var objects = [{
        "make": "BMW",
        "model": "i3",
        "maxRange": 81,
        "price": "42,400",
        "body": "Hatchback"
    }, {
        "make": "Chevrolet",
        "model": "Spark EV",
        "maxRange": 82,
        "price": "25,120",
        "body": "Hatchback"
    }, {
        "make": "Kia",
        "model": "Soul EV",
        "maxRange": 90,
        "price": "31,950",
        "body": "Wagon"
    }, {
        "make": "Tesla",
        "model": "Model S",
        "maxRange": 303.2,
        "price": "75,000",
        "body": "Sedan"
    }, {
        "make": "Tesla",
        "model": "Model X",
        "maxRange": 257,
        "price": "83,000",
        "body": "SUV"
 }]

我尝试使用_matches,但它似乎与数组不匹配。这是我的尝试

_.filter(objects, _.matches(query))

2 个答案:

答案 0 :(得分:1)

嗯,我不知道如何处理lodash,但我们当然可以用两行代码来处理vanillaJS。

var query = { "body": ["Hatchback", "Sedan"] }; 
var filteredObjArray = objects.filter(obj => query.body.includes(obj.body)))

希望有帮助:)。

答案 1 :(得分:1)

您可以将JS .filter.every一起使用来检查多个属性。如果查询属性是数组,则使用.include进行比较,如果不进行简单比较:

function multipleFilter(arr, query) {
  var queryKeys = Object.keys(query); // create an array of the keys in the query object

  return arr.filter(function(item) {
    return queryKeys.every(function(key) { // use .every on the keys so if one fails, the item is filtered out
      var keyData = item[key]; // get the data of the key from the item
      var keyQuery = query[key]; // get the query from query object
      return Array.isArray(keyQuery) ? keyQuery.includes(keyData) : keyQuery === keyData; // if the query is an array use include, if not use comparison
    });
  });
}

var objects = [{
  "make": "BMW",
  "model": "i3",
  "maxRange": 81,
  "price": "42,400",
  "body": "Hatchback"
}, {
  "make": "Chevrolet",
  "model": "Spark EV",
  "maxRange": 82,
  "price": "25,120",
  "body": "Hatchback"
}, {
  "make": "Kia",
  "model": "Soul EV",
  "maxRange": 90,
  "price": "31,950",
  "body": "Wagon"
}, {
  "make": "Tesla",
  "model": "Model S",
  "maxRange": 303.2,
  "price": "75,000",
  "body": "Sedan"
}, {
  "make": "Tesla",
  "model": "Model X",
  "maxRange": 257,
  "price": "83,000",
  "body": "SUV"
}];

var query1 = {
  "body": ["Hatchback", "Sedan"]
};

var query2 = {
  "body": ["Hatchback", "Sedan"],
  make: "BMW"
};


console.log('query1', multipleFilter(objects, query1));

console.log('query2', multipleFilter(objects, query2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>