首页 > 解决方案 > 根据嵌套数组中的值过滤数组

问题描述

我有一个对象,我想根据嵌套数组是否包含某个值进行过滤。

数据

{
  "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(),但我无法让它发挥作用。我认为这是因为数组是嵌套的,但我不确定如何到达它。

我将如何过滤以仅返回类型与过滤值匹配的那些条目?

标签: javascriptarrays

解决方案


您可以使用Array.someArray.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"))


推荐阅读