1

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?

2
  • 1
    Show us what you tried that you were not able to get working. Commented Aug 24, 2020 at 17:13
  • 1
    Don't use the json tag (or term) for JavaScript object literals. Commented Aug 24, 2020 at 17:31

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

instead of some I'd use indexOf, but that's a good solution
Yes @LuísMestre that also works absolutely fine. But instead of again having a condition to check !== -1 I preferred something which by default provide a boolean value.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.