Home > OS >  Checking if object contains X in jQuery / ajax
Checking if object contains X in jQuery / ajax

Time:03-14

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'));
    
    });

CodePudding user response:

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');
    }
});

CodePudding user response:

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
  • Related