0
I’m making a search system and with a problem to show the name of the arrays inside the object.
The object is in this style:
let item = {
descricao: "Casa",
id: 123,
localizacoesFilho: [
{
descricao: "Cozinha",
id: 124
},
{
descricao: "Garagem",
id: 125
}
]
}
And the code I’m using is this:
searchLocalizacao(item) {
if (item.descricao) {
if(item.localizacoesFilho && item.localizacoesFilho.length > 0) {
return item.localizacoesFilho[0].descricao.toLowerCase().indexOf(this.q.toLowerCase()) == -1;
}
item.descricao.toLowerCase().indexOf(this.q.toLowerCase()) == -1;
}
};
This code is showing the items that do not have an array normally, but the items that have an array it only shows the name if it is the first one, as I do to show the name of the array that the user is searching for regardless of its position?
Obs: the this.q
is storing the letters I type in the input.
Leo, the code you passed was not a problem, but the way I put the code is making it show the elements that have child regardless of what I type. For example, if I type Administration and the element that has a child is called Cafeteria, it shows the Administration and the Cafeteria. I can’t put the code here, so I put it on Jsfiddle: link Note: I have tried to leave only your code, but it adds all other elements of the screen and leaves only those who have children. Thank you, from now on.
– guickz
So we can start from the beginning, if your function should return a
array
make her return onearray
always, try as much as possible not to mix back types as this may be an unnecessary headache, so if your array doesn’t have any elements don’treturn item.descricao.toLowerCase().indexOf(pesquisarPor) == -1
but doreturn []
this way it will always be an empty array or with elements.– Leo Letto
For the problem of showing or not other elements in HTML, seems to me to be a problem for another question, the scope of this was to filter the elements in to the array and return the elements that pass a given test, and this seems to me to be solved, if you want to know why of other problems it is better to ask another question by putting the code you are using and explain the problem in detail
– Leo Letto