1

I have an object,

data: [
    {
     "name": "aaa",
     "email": null,
     "username": "bbb",
     "age": 56,
     "dob": null,
  },
  {
     "name": "ddd",
     "email": null,
     "username": "ggg",
     "age": 46,
     "dob": null,
  },
]

If i append the data like,

$.each(data,function(i,e){
  .........
  $(".email").text(e.email);
  .........
})

I got an error

Cannot read property 'email' of null

So, If there is an null value in the object i want to append it as a empty string. How can i make it.

3
  • How does this data throw "Cannot read property 'email' of null" error? Commented Sep 24, 2019 at 12:30
  • 1
    that error is not saying that e.email is null, it is saying e is null and with that code, that is impossible. Commented Sep 24, 2019 at 12:31
  • You are right @epascarello, i missed one record so that caused me an error. thank you Commented Sep 24, 2019 at 12:36

2 Answers 2

2
$.each(data,function(i,e){
  .........
  $(".email").text(e && e.email ? e.email : '');
  .........
})

This will add email if exists, otherwise, an empty string.

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

Comments

-1

In case attribute is null, one can go with -

   $.each(data,function(i,e){
     $(".email").text(e.email == null ? "": e.email);
    });

In case possibility of null object, one can go with -

$.each(data,function(i,e){
  $(".email").text(e != null && e.email ? e.email : "");
  console.log(e != null && e.email ? e.email : "");
});

7 Comments

This will error if email property is not present, as it seems the case on the original question.
@avcajaraville the error in the question comes from the fact that e is null, not the email property.
Tried this on Chrome dev tools, it will not give any error even if property is not present in object, please try once on browser.
What about if there is an object but no email property? (e&&e.email)||""
@Durgesh With e.email == null ? "": e.email you only test for null, and it will result in "undefined" if the property is missing (or is set to undefined)
|

Your Answer

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