0

I have the code bellow and I'm trying to console.log the information from message of each array. The problem is there are some undefined "payload". What can I do to ignore the undefined values and keep iterating through the arrays?

const repositoriesActivities = await getUserActivities(userName)
   
    for (let i = 0; i < repositoriesActivities.length; i++) {
        let activities = repositoriesActivities[i].payload.commits[i].message;
        
        if (activities !== undefined){
           console.log(activities)
        }    
      }
1
  • 1
    You can use optional chaining ?. Commented May 22, 2022 at 16:49

2 Answers 2

2

You can use ? operand to check. Example:

const repositoriesActivities = await getUserActivities(userName)
   
    for (let i = 0; i < repositoriesActivities.length; i++) {
        let activities = repositoriesActivities[i]?.payload?.commits[i]?.message;
        
        if (activities){
           console.log(activities)
        }    
      }

Check this to get more information about optional chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Sign up to request clarification or add additional context in comments.

2 Comments

Thank, but the error persists. The code prints the first information, but the second array's "payload" is empty, then it returns the error.
Hi, maybe there is something that we missed. Can you check this code. I have created a simple array and using for loop. After 2 steps you can see we get different console on this example: pastebin.pl/view/c2c45d9a
1

this means the object "commits" is empty. Can you try:

const repositoriesActivities = await getUserActivities(userName)
   
    for (let i = 0; i < repositoriesActivities.length; i++) {
        let activities = null
if(repositoriesActivities[i] && repositoriesActivities[i].payload && typeof repositoriesActivities[i].payload.commits === "object" && repositoriesActivities[i].payload.commits.length >= (i+1) && repositoriesActivities[i].payload.commits[i].message){
   activities = repositoriesActivities[i].payload.commits[i].message
} 
   
        
        if (activities !== null){
           console.log(activities)
        }    
      }

1 Comment

Thanks, but I'm receiving this error: Cannot read properties of undefined (reading 'length')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.