When I try to get a value from an array, we output [object Object]

Code:

$.getJSON("../json/" + str + ".json", function(data) { var vname = data.vname; var src = data.src; var desc = data.desc; var date = data.date; var comments = data.comments; //"проблемный" массив var cmt = comments[i]; //i == 2 alert("cmt= " + cmt); //это выводит [object Object] var tcmt = cmt[0]; alert("tcmt= " + tcmt); var idpcmt = (_.invert(hash))[tcmt]; alert("idpcmt= " + idpcmt); }); 

Here is the array entry in json:

 "comments":{"1":{"-1":"1"},"2":{"-2":"2"},"3":{"11":"Jsjdjsj"},"4":{"11":"Jsjdjsjhgfd"}} 
  • And where is your array? I see an object consisting of objects. Try alert (JSON.stringify (data.comments ["1"])) and get the first object. - haswell
  • Damon Haswell, tried, in response all the same [object Object] - Ivan Repin
  • Displays the first element of the jsfiddle.net/xpvt214o/561117 object - haswell

1 answer 1

In your code there was an implicit conversion from an object to a string, which gives the result in the form [object Object] . Use JSON.stringify() to explicitly convert an object to a json format string.

 $.getJSON("../json/" + str + ".json", function(data) { var vname = data.vname; var src = data.src; var desc = data.desc; var date = data.date; var comments = data.comments; //"проблемный" массив var cmt = comments[i]; //i == 2 alert("cmt= " + JSON.stringify(cmt)); //теперь это будет выводить объект в строковом json формате var tcmt = cmt[0]; alert("tcmt= " + tcmt); var idpcmt = (_.invert(hash))[tcmt]; alert("idpcmt= " + idpcmt); });