I have a state with an array of objects:
const [UploadLogos, setUploadLogos] = useState([
{ url: null, name: null},
{ url: 'anyURL', name: null},
{ url: null, name: null}
]);
I want to get the length of this array if the key url
is not null.
I do it like this:
const UploadedLogosWithURL = UploadLogos.map((logo) => {
return logo.url !== null;
})
<button onClick={() => { console.log(UploadedLogosWithURL.length) }}>
Click
</button>
But it doesn’t work. Where am I going wrong?
4
Answers
Why don’t you just use filter()? it would be something like:
const newArray = UploadLogos.filter(item => item.url !== null);
<button onClick={() => { console.log(newArray.length) }}> Click </button>
Hope it helps!
@kanishk6103 got it right. Although, I would like to make it more short by simply returning the URL key ( it will check if its not null )
This should also do the job.
You can filter your state, then get the length of your filtered array.
Your code actually works just fine, the problem is the use of
.map()
, what’s happening is that you’re creating a new array, populated with the boolean results of whether or notlogo.url !== null
i.e.
[false, true, false]
from MDN:
The solution of @kanishk6103 would solve it, but a small enhancement is that you don’t have to use the comparison because you’re checking for booleans,
so a more concise way would be: