lodash - Lodash:过滤多个属性
问题描述
我是 lodash 的新手。
我在使用 lodash 过滤时遇到问题。我有一个深层嵌套的 json 对象,如果 productName = 'Lotto' 和 board selectionMethod = "AUTOPICK",我想过滤它
当我尝试下面的解决方案时,它会返回所有结果而不是过滤。我尝试了多种方法来做到这一点,但我总是得到所有结果。
有人可以提供建议吗?
var results = {
"buyTicketDetails": {
"result": 0,
"message": "Success",
"product": [
{
"productName": "Lotto",
"displayPromoMessage": false,
"drawDetails": [
{
"drawTypeDescription": "REGULAR DRAW",
"drawAttribute": "EVENING",
"drawStartDate": "2019-01-12T00:00:00.000-05",
"drawEndDate": "2019-01-12T00:00:00.000-05"
},
{
"drawTypeDescription": "SPECIAL DRAW",
"drawAttribute": "EVENING",
"drawStartDate": "2019-01-12T00:00:00.000-05",
"drawEndDate": "2019-01-12T00:00:00.000-05"
}
],
"board": [
{
"boardType": "REGULAR",
"selectionMethod": "AUTOPICK",
"selectionSet": [
"2",
"4",
"10",
"12",
"17",
"31"
]
},
{
"boardType": "RAFFLE",
"selectionMethod": "SYSTEMPICK",
"selectionSet": [
"40001722-01"
]
}
]
},
{
"productName": "Encore",
"displayPromoMessage": false,
"drawDetails": [
{
"drawTypeDescription": "REGULAR DRAW",
"drawAttribute": "EVENING",
"drawStartDate": "2019-01-12T00:00:00.000-05",
"drawEndDate": "2019-01-12T00:00:00.000-05"
}
],
"board": [
{
"boardType": "REGULAR",
"selectionMethod": "SYSTEMPICK",
"selectionSet": [
"3440514"
]
}
]
}
]
}
}
const filterCat = _.filter(results, { product: [
{
productName: "Lotto",
board: {
selectionMethod: "AUTOPICK"
}}
]
}
);
console.log(filterCat);
解决方案
使用纯 JS。
您也可以使用 Javascript 的过滤器功能来做到这一点。
filter 函数实际上适用于数组,所以我们先使用 map 循环将对象添加到数组中,然后使用 filter 函数只获取我们需要的数据!。
let Product = results.buyTicketDetails.product
let getSelectionMethods=(index) => Product[index].board.map((d,i)=>d.selectionMethod)
let getTargetedProducts =(Name,Method)=> Product.map((d,i)=>{
if(Product[i].productName==Name && getselectionMethods(i).indexOf(Method) !==-1){
return d
}
})
let FilteredProducts = getTargetedProducts("Lotto","AUTOPICK").filter((d)=>d !==undefined)
console.log(FilteredProducts)
推荐阅读
- ms-access - 如何从表字段值中默认表单字段值?(MS 访问)
- arrays - groupby() 在 julia 中使用两个数组?
- java - 为什么选择 ResponseEntity
是通用的吗? - javascript - 如何将 onclick 事件添加到 Next.js 中的字符串呈现按钮?
- python - Plotly Express 热图无法正常工作
- r - 提取R数据框中除数字外的所有列
- python - Python:如何在下一个不同的字符串重复出现时搜索字符串并打印
- android - 如何有效地显示来自 URL 的图像
- c++ - 在 Xcode 中构建和运行 C+/Juce 项目时在哪里定义程序入口点?
- node.js - Feathers js - 谷歌登录导致删除现有用户