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.
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.
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.
CodePudding user response:
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))