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"和颜色"怀特" ?
答案 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;
普通Javascript
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;