我正在尝试通过值为非空的对象键来过滤对象数组
var collection = [
{
"season": "ETE 18",
"group": "GRBABY",
"market": "ALL",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
{
"season": "ETE 18",
"group": "MEN",
"market": "ALL",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
{
"season": "ETE 18",
"group": "GRBABY",
"market": "NONE",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
]
var filterList = {season: "", group: "GRBABY", market: "ALL", department: "",
skuType: ""}
var result = _.filter(collection , proPack => {
if (filterList.group !== '') {
return proPack.group === filterList.group;
} else {
return proPack;
}
});
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
这对我来说只适用于一个过滤器,但是当它们有值时,我无法找到过滤所有其他键的方法。
结果应该是:
result = [
{
"season": "ETE 18",
"group": "GRBABY",
"market": "ALL",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
} ]
答案 0 :(得分:2)
您可以删除空属性:
var collection = [{
"season": "ETE 18",
"group": "GRBABY",
"market": "ALL",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
{
"season": "ETE 18",
"group": "MEN",
"market": "ALL",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
{
"season": "ETE 18",
"group": "GRBABY",
"market": "NONE",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
}
]
var filterList = {season: "", group: "GRBABY", market: "ALL", department: "",
skuType: ""}
var filterList = _.omitBy(filterList, _.isEmpty) // { group: "GRBABY", market: "ALL" }
var result = _.filter(collection, filterList)
console.log(filterList, result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
答案 1 :(得分:1)
我认为这应该做你想要的。您是否忽略了filterList
中空值正确的键?
var collection = [
{
"season": "ETE 18",
"group": "GRBABY",
"market": "ALL",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
{
"season": "ETE 18",
"group": "MEN",
"market": "ALL",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
{
"season": "ETE 18",
"group": "GRBABY",
"market": "NONE",
"department": "ALL",
"skuType": "ALL",
"orderType": "ASE",
"packagingType": "CI"
},
]
var filterList = {season: "", group: "GRBABY", market: "ALL", department: "",
skuType: ""}
var doFilter = function(arr, filterObj) {
return arr.filter(propack => {
for (key in filterObj) {
if (filterObj[key] && filterObj[key] !== propack[key]) {
return false;
}
}
return true;
});
};
console.log(doFilter(collection, filterList));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;