PaulVO
PaulVO

Reputation: 309

Filter array based on value in nested array

I have an object that I want to filter based on whether or not a nested array contains a certain value.

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" ]
    }
  ]
}

Now I want to return a new array based on whether a specific value is present. E.g. if I were to filter by ad, only the last 2 entries would be returned:

Filtered by ad

{
  "content": [
    {
      "text" : "Want #desiredResult#? Use #productName#",
      "types" : [ "ad", "email" ]
    },
    {
      "text" : "Your Search For #solution# Ends Here",
      "types" : [ "ad", "email" ]
    }
  ]
}

I initially thought I could use Array.prototype.filter(), but I haven't been able to get that to work. Which I assume is because the array is nested, but I'm unsure on how to reach it.

How would I filter to return only those entries where the type matches a filtered value?

Upvotes: 1

Views: 230

Answers (1)

Nithish
Nithish

Reputation: 5999

You can make use of Array.some and Array.filter in order to achieve what you are looking for.

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"))

Or Array.includes with Array.filter will also work. You can refer below for the same

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"))

Upvotes: 2

Related Questions