console.log(result) returns [object Object]. How do I get result.name?

Wassim Benhamida picture Wassim Benhamida · Dec 26, 2016 · Viewed 207.8k times · Source

My script is returning [object Object] as a result of console.log(result).

Can someone please explain how to have console.log return the id and name from result?

$.ajaxSetup({ traditional: true });

var uri = "";

$("#enginesOuputWaiter").show();    
$.ajax({
    type: "GET",
    url: uri,
    dataType: "jsonp",
    ContentType:'application/javascript',
    data :{'text' : article},
    error: function(result) {
        $("#enginesOuputWaiter").hide();
        if(result.statusText = 'success') {
            console.log("ok");
            console.log(result);
        } else {
            $("#enginesOuput").text('Invalid query.');
        }
    }
});

Answer

suvartheec picture suvartheec · Dec 26, 2016

Use console.log(JSON.stringify(result)) to get the JSON in a string format.

EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty and access the property if it does exist:

var obj = {id : "007", name : "James Bond"};
console.log(obj);                    // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj));    //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
    console.log(obj.id);             //007
}