One of my alerts is giving the following result:
[object Object]
What does this mean exactly? (This was an alert of some jQuery object.)
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 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(""))
The alert() function can't output an object in a read-friendly manner. Try using console.log(object) instead, and fire up your browser's console to debug.
If you are popping it in the DOM then try wrapping it in
<pre>
<code>{JSON.stringify(REPLACE_WITH_OBJECT, null, 4)}</code>
</pre>
makes a little easier to visually parse.
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))
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 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)
Solution: I got it to work by simply using a comma:
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)