[英]Filter array based on value in nested array
我有一個對象,我想根據嵌套數組是否包含某個值來過濾該對象。
數據
{
"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
過濾, 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.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和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.includes(filterBy) }) } console.log(filterByType(data.content, "ad"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.