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

JavascriptJqueryArraysJsonAjax

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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
}

Solution 2 - Javascript

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWassim BenhamidaView Question on Stackoverflow
Solution 1 - JavascriptsuvartheecView Answer on Stackoverflow
Solution 2 - Javascriptuser6347904View Answer on Stackoverflow