skip to Main Content

How would I go about checking if a Object returned by a API contains X?

This is the closest I have gotten, without getting any errors:

$.ajax(settings).done(function (response) {

var email_response = {response};         

if (Object.values((JSON.stringify(email_response))).indexOf('"response"') > -1) {
            console.log('Is valid');
         
         else (console.log('Not valid'));
});

After running it results with the "Not valid" response from the if else function, even though the text "valid" is present in the return where "Is valid" would be the expected result.

Stringified using console.log(JSON.stringify(email_response)); this is what is returned from the API:

{"response":{"address":"[email protected]","status":"valid","sub_status":"role_based_catch_all","free_email":false,"did_you_mean":null,"account":"test","domain":"domain.com","domain_age_days":"10116","smtp_provider":"","mx_found":"true","mx_record":"mx.domain.com","firstname":null,"lastname":null,"gender":null,"country":null,"region":null,"city":null,"zipcode":null,"processed_at":"2022-03-12 12:41:38.306"}}

I have tried to not stringify it as well, but this has the same result as explained above.

The following does also not see the specified text as present:

    Object.keys(email_response).forEach(function(key) {
    if ((email_response)[key] == 'valid') {
        console.log('Is valid');}
        else (console.log('Not valid'));
    
    });

2

Answers


  1. you dont have to stringify if you want to get some data

    $.ajax(settings).done(function (response) {
    
    var status= response.status; // valid
    
    //or 
    console.log("status",response.status); // valid or undefined
    
     }); 
    

    but if for some reasons you like to create a new object, use this code

    var email_response = {"response":response}; 
    
    var status= email_response.response.status; // valid
    
    Login or Signup to reply.
  2. valid is not a key, it’s a value. You need to check for the key status like this.

    $.ajax(settings).done(function (response) {
    
        if (response.hasOwnProperty('status') && response.status === 'valid') {
            console.log('Is valid');
             
        } else {
            console.log('Not valid');
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search