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 alerting 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 already explained the reason for [object object], I would like to elaborate on how to inspect the object's value. There are three options that come to my mind:
JSON.stringify(JSONobject)console.log(JSONobject)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(""))
Another option is to use JSON.stringify(obj)
For example:
exampleObj = {'a':1,'b':2,'c':3};
alert(JSON.stringify(exampleObj))
In my case I was getting [Object, Object] because I was doing
console.log("particular_object" + particular_object)
Instead of
console.log("particular_object")
console.log(particular_object)
I guess adding another string in the same console.log of an object prevents the object from loading..
But most cases you just have to do:
JSON.stringify(particular_object))
UPDATE: Cool comment/clarification by @stevejboyer below!
If you are getting this error from passing text plus an object in the same console.log method by using a plus sign(+); You can actually use a comma to avoid any errors and still console text along with your object.
By doing this instead:
console.log("particular_object", particular_object)
console.log('particular object', particular_object) to consolidate the two console.log calls to one lineIn my case I got [object Objects] when I did the following:
const person2 = {
name: "Jo",
age: 27,
address: {
city: "Some city",
state: "Some state"
}
}
const requestedPerson = person2
const {
name,
age,
address,
favFood = "Not defined"
} = requestedPerson
console.log(`Address: ${address}`);
And it was the same as using:
console.log("Address: " + address)
I got it to work by passing it as the second argument:
console.log("Address:", address)
Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)