-1

I have some problem, I have an array like this

var obj = [{'person': {'name: 'foo', 'email': 'email.com'}, {'person': {'name: 'foo'}]

if i loop inside var obj, and want to get value email like this :

$.each(obj, function(index, value) {
    console.log(value.person.email)
}

if I do like that, it shows an error because cannot read the property email.

how I pass it when the person does not have email ? or is there a way to create conditions like isset on php

p u
  • 1,395
  • 1
  • 17
  • 30
Newbie 123
  • 254
  • 4
  • 19

2 Answers2

0

You can use in operator to check if object has that key present or not like this.

Please note, there is the syntax error in your array. I have corrected it.

var obj = [{'person': {'name': 'foo', 'email': 'email.com'}}, {'person': {'name': 'foo'}}];

$.each(obj, function(index, value) {
  if ('email' in value.person){
    console.log(value.person.email);
  }      
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Mayank Patel
  • 1,563
  • 1
  • 14
  • 19
0

You can use simple !! which will return boolean value.

var obj = [{'person': {'name': 'foo', 'email': 'email.com'}}, {'person': {'name': 'foo'}}];

$.each(obj, function(index, value) {
    if(!!value.person.email){
      console.log(value.person.email);
    } else {
      console.log("Email not available");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59