1

I have this example:

var data={
  city:{
    street:{
      houses:[]
    }
  }
}

alert(data.city.street.houses?.[0].person);

    var data={
      city:{
        street:{
          houses:[]
        }
      }
    }

    alert(data.city.street.houses?.[0].person);

this would show an error because it does not exist houses[0], how can I avoid having errors but in case houses[0] does exist, continue with the nesting?

doing this, I am getting errors:

enter image description here

how can I do it?

3
  • Sorry, can you please clarify your question? Commented Oct 12, 2021 at 2:51
  • I think you put the optional chaining operator in the wrong place. You might have meant to put it after the [0] Commented Oct 12, 2021 at 2:53
  • @MrMythical I added some details, thanks Commented Oct 12, 2021 at 3:04

1 Answer 1

1

Just add another chaining operator after the array item reference:

var data = {
  city: {
    street: {
      houses: []
    }
  }
}

let res = data.city.street.houses?.[0];
res = res != undefined ? res.person : 'no value';
console.log(res);

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

4 Comments

I add some details in my question, can you see again please?
@yavgz something is wrong with your IDE if it's giving an error with this answer. Make sure you're on the latest version
I know that maybe it is out of the scope of the question, but maybe you know how to help me, I can make a ternary operator in the case that the nesting becomes undefined?
@yavgz I've updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.