Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter multiple nested arrays with objects

I have an array nested with an array of objects, the problem is that I don’t understand how to filter the entire property by title at once.

enter image description here

At the moment, filtering for the title property works fine for me, but it only works for the top level, that is, it does not work inside the elems array.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At the moment, my code looks like this

state: {
    searchValue: "",

    categories: [
        {
            title: "about",
            open: false,
            elems: [{ title: "portfolio" }],
        },
        {
            title: "services",
            open: false,
            elems: [{ title: "jobs" }],
        },
    ],
},

getters: {
    categories(state) {
        return state.categories.filter(item => {
            return item.title.toLowerCase().includes(state.searchValue.toLowerCase())
        })
    }
}

And in the end, for a better understanding, I would like to tell what I want to achieve when the user enters the word about or portfolio into the input, for example, I want to show the first object if the word jobs or services is entered, I want to show the second object, but again, the title property of the first level works for me, but the title property inside the elems array does not work.

>Solution :

You can try with some for nested array:

let searchValue = "about"

const categories = [
  {title: "about", open: false, elems: [{ title: "portfolio" }],},
  {title: "services", open: false, elems: [{ title: "jobs" }, { title: "about" }],},
]

function cats(state) {
  return state.filter(item => {
    return item.title.toLowerCase().includes(searchValue.toLowerCase()) ||
      item.elems.some(e => e.title.toLowerCase().includes(searchValue.toLowerCase()))
  })
}

console.log(cats(categories))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading