how to use the array.find method to find an attribute of an array that is formed by the contents of the localStorage?

Asked

Viewed 19 times

0

I have an empty array that receives via push the content of the localstorage (which is also an array),

however, when I give a.find vector to find the value of an attribute, such as _name, it does not return the result, presenting the Undefined error.

const vetor = []

vetor.push(window.localStorage.getItem ('localCadastro'));

const resultado = vetor.find (atributo => atributo._nome == 'teste');

when I give a console.log (vector), the result is this:

["[{\"_cpf\":\"\",\"_conta\":\"\",\"_nome\":\"teste\"}]"]

but when I give a console.log (result), the result is this:

undefined

I want to use find to find a specific content in the array that is in localStorage.

ps: I use window.localStorage because I am trying to query localStorage of index.html and localstorage is being saved in another.html deletine.

1 answer

0


The localStorage does not store arrays or objects, it stores only strings.

See that item localCadastro is being returned as a string, not as a array, you should be parsing this value to get the array:

const vetor = JSON.parse(window.localStorage.getItem('localCadastro'));

There’s no need to do it either push, as you would be inserting an array within another array, which I believe is not your goal.

Now you can make the find normally, as you yourself put in the question:

const resultado = vetor.find(atributo => atributo._nome == 'teste');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.