javascript - 根据嵌套数组中的值过滤数组
问题描述
我有一个对象,我想根据嵌套数组是否包含某个值进行过滤。
数据
{
"content": [
{
"text" : "#number# Tips to Get #solution#",
"types" : [ "email"]
},
{
"text" : "Want #desiredResult#? Use #productName#",
"types" : [ "ad", "email" ]
},
{
"text" : "Your Search For #solution# Ends Here",
"types" : [ "ad", "email" ]
}
]
}
现在我想根据是否存在特定值返回一个新数组。例如,如果我按 过滤ad
,则只会返回最后 2 个条目:
筛选条件ad
{
"content": [
{
"text" : "Want #desiredResult#? Use #productName#",
"types" : [ "ad", "email" ]
},
{
"text" : "Your Search For #solution# Ends Here",
"types" : [ "ad", "email" ]
}
]
}
我最初以为我可以使用Array.prototype.filter()
,但我无法让它发挥作用。我认为这是因为数组是嵌套的,但我不确定如何到达它。
我将如何过滤以仅返回类型与过滤值匹配的那些条目?
解决方案
您可以使用Array.some和Array.filter来实现您正在寻找的东西。
let data = {
"content": [
{
"text" : "#number# Tips to Get #solution#",
"types" : [ "email"]
},
{
"text" : "Want #desiredResult#? Use #productName#",
"types" : [ "ad", "email" ]
},
{
"text" : "Your Search For #solution# Ends Here",
"types" : [ "ad", "email" ]
}
]
}
const filterByType = (data, filterBy) => {
return (data || []).filter(d => {
return d.types.some(type => type === filterBy)
})
}
console.log(filterByType(data.content, "ad"))
或者Array.includes withArray.filter
也可以。您可以参考以下内容
let data = {
"content": [{
"text": "#number# Tips to Get #solution#",
"types": ["email"]
},
{
"text": "Want #desiredResult#? Use #productName#",
"types": ["ad", "email"]
},
{
"text": "Your Search For #solution# Ends Here",
"types": ["ad", "email"]
}
]
}
const filterByType = (data, filterBy) => {
return (data || []).filter(d => {
return d.types.includes(filterBy)
})
}
console.log(filterByType(data.content, "ad"))
推荐阅读
- windows - TStatusBar 控件中的模糊文本
- r - 在 dplyr 中为 group_by 调用变量名的函数 - 如何在函数中对这个变量进行矢量化?
- python - 使用 direnv 激活 virtualenv 不会激活 virtualenv
- bufferedreader - Java-UnchekedIOException:从 ClientHttpResponse 读取时文件过早结束
- statistics - 不同分布的 MP 检验
- android - 我在使用 compile 'com.theartofdev.edmodo:android-image-cropper:2.7.+' 这个库来裁剪图像时遇到问题
- python - LabelEncoder fit_transform() 函数中的问题
- vba - excel vba - 创建一个包含数组条目的集合
- asp.net - ASP.NET MVC Identity vs ASP.Net core 2.1 Identity(它们之间的交叉身份验证)
- sql-server-2008 - 请清楚地解释 CTE 查询?