What does [object Object] mean? (JavaScript)
One of my alerts is giving the following result:
[object Object]
What does this mean exactly? (This was an alert of some jQuery object.)
It means you are alerting an instance of an object. When alert
ing the object, toString()
is called on the object, and the default implementation returns [object Object]
.
var objA = {};
var objB = new Object;
var objC = {};
objC.toString = function () { return "objC" };
alert(objA); // [object Object]
alert(objB); // [object Object]
alert(objC); // objC
If you want to inspect the object, you should either console.log
it, JSON.stringify()
it, or enumerate over it's properties and inspect them individually using for in
.
As @Matt answered the reason of [object object]
, I will expand on how to inspect the value of the object. There are three options on top of my mind:
-
JSON.stringify(JSONobject)
-
console.log(JSONobject)
- or iterate over the object
Basic example.
var jsonObj={
property1 : "one",
property2 : "two",
property3 : "three",
property4 : "fourth",
};
var strBuilder = [];
for(key in jsonObj) {
if (jsonObj.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " + jsonObj[key] + "\n");
}
}
alert(strBuilder.join(""));
// or console.log(strBuilder.join(""))
https://jsfiddle.net/b1u6hfns/