skip to Main Content

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


  1. 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!

    Login or Signup to reply.
  2. @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 )

    const [UploadLogos, setUploadLogos] = useState([
      { url: null, name: null},
      { url: 'anyURL', name: null},
      { url: null, name: null}
    ]); 
    
    <button 
       onClick={() => { 
          console.log(UploadLogos.filter((logo) => logo.url)).length) 
       }}
    >
      Click
    </button>
    

    This should also do the job.

    Login or Signup to reply.
  3. You can filter your state, then get the length of your filtered array.

    const initialLogos = [
      { url: null, name: null},
      { url: 'anyURL', name: null},
      { url: null, name: null}
    ]
    
    const [logos, setLogos] = useState(initialLogos)
    
    const logosWithUrl = logos.filter(logo => logo.url !== null);
    const logosWithUrlLength = logosWithUrl.length;
    
    Login or Signup to reply.
  4. 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 not logo.url !== null
    i.e. [false, true, false]

    from MDN:

    The map() method of Array instances creates a new array populated with
    the results of calling a provided function on every element in the
    calling array.

    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:

    UploadLogos.filter(logo => logo.url);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search