如何在对象数组中添加多个过滤条件?

时间:2016-11-15 10:41:38

标签: javascript lodash

var products = [{
  "sku": "SKU001",
  "size": "XS",
  "color": "Red"
}, {
  "sku": "SKU002",
  "size": "S",
  "color": "Blue"
}, {
  "sku": "SKU003",
  "size": "XS",
  "color": "Black"
}, {
  "sku": "SKU004",
  "size": "M",
  "color": "Red"
}, {
  "sku": "SKU005",
  "size": "M",
  "color": "White"
}]

我如何获得尺寸为" XS"的产品?和" S"和颜色"怀特" ?

1 个答案:

答案 0 :(得分:0)

基本上,你可以使用一个回调来测试对象的所需值,如果匹配则返回true

function (p) {
    return (p.size === 'XS' || p.size === 'S') && p.color === 'White';
}



var products = [{ "sku": "SKU001", "size": "XS", "color": "Red" }, { "sku": "SKU002", "size": "S", "color": "Blue" }, { "sku": "SKU003", "size": "XS", "color": "Black" }, { "sku": "SKU004", "size": "M", "color": "Red" }, { "sku": "SKU005", "size": "M", "color": "White" }, { "sku": "test1", "size": "S", "color": "White" }, { "sku": "test2", "size": "XS", "color": "White" }],
    result = _.filter(products, function (p) {
        return (p.size === 'XS' || p.size === 'S') && p.color === 'White';
    });

console.log(result);

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

普通Javascript

&#13;
&#13;
var products = [{ "sku": "SKU001", "size": "XS", "color": "Red" }, { "sku": "SKU002", "size": "S", "color": "Blue" }, { "sku": "SKU003", "size": "XS", "color": "Black" }, { "sku": "SKU004", "size": "M", "color": "Red" }, { "sku": "SKU005", "size": "M", "color": "White" }, { "sku": "test1", "size": "S", "color": "White" }, { "sku": "test2", "size": "XS", "color": "White" }],
    result = products.filter(function (p) {
        return (p.size === 'XS' || p.size === 'S') && p.color === 'White';
    });

console.log(result);
&#13;
&#13;
&#13;