Started learning javascript and currently going thru object topic.
<!DOCTYPE html>
<html>
<body>
<h3>object prop access</h3>
<p id="demo"></p>
<p id="test"></p>
<script>
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value1';
//console.log(object[bar]);
document.getElementById("demo").innerHTML = "Object property:"+object[bar];
document.getElementById("test").innerHTML = "Object property object[foo]:"+object[foo];
</script>
</body>
</html>
When I run this program it prints value "value1" , "value1" in separate lines.
My question is there is no property name "bar" defined for "object" then why object[bar] prints value "value1" - which is assigned to object[foo].
--Divyesh
Because an object property has a key and a value. The key is always a string. When you try to set a key for a value for which that key is a variable and it as an object, it will have the .toString method of the object/variable called which is this case is will return [object Object]
so bar and foo will be equivalent when converted to a string.
So, you can think of it as accessing the object like this object["[object Object]"]
bar.toString() // "[object Object]"
foo.toString() // "[object Object]"
Related
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'anu';
console.log(object[bar]);
The above code outputs "anu".
toString method typecast the non-string object into string object.
In the above code object[bar] outputs the value as 'anu'.
Document says 'since both foo and bar are converted to the same string'
I can't able to understand the java script toString method on this code.
can anybody please explain how it works?
When you use foo's value as a property name, it calls toString on the foo like object[foo.toString()] = 'anu', which if not overridden, will return the same value for every object, which is '[object Object]'
So actually you have a property which name is '[object Object]'.
Below console.logs will assure that you have a property with name '[object Object]'.
var foo = {unique_prop: 1};
var object = {};
object[foo] = 'anu';
console.log(`foo.toString() - ${foo.toString()}`);
console.log(`object.toString() - ${object.toString()}`);
console.log(`object.toString() === foo.toString() ? - ${object.toString() === foo.toString()}`);
for(var prop in object) {
console.log(prop);
}
I have the following code snippet below:
var obj = new Object();
var foo = new Object();
var bar = new Object();
obj[foo] = 'hello';
obj[bar] = 'hi'
console.log (obj[foo])
It prints "hi". Why is this?
Objects in JS can have string keys only. When you do obj[foo] actualy you do obj[foo.toString()].
Your code will be
obj["[object Object]"] = 'hello';
obj["[object Object]"] = 'hi'
console.log (obj["[object Object]"])
Objects need a string as reference. Any variable used as key is casted to string with the prototype toString and here you get for this '[object Object]', which is used as key.
var obj = new Object(),
foo = new Object(),
bar = new Object();
obj[foo] = 'hello';
obj[bar] = 'hi'
console.log (obj[foo]);
console.log('' + foo); // force object to use toString() method
console.log (obj['[object Object]']);
you are assigning the object obj with keys which are objects (foo & bar).
When keys given to object are objects themselves then the following is assigned as the key value
[object Object]
this simply means that your 1st assignment
obj[foo] = 'hello'
created key [object Object] and made its value "hello";
then your second assignment did the same, but since the key [object Object] is already present, the previous value got overridden with "hi".
Now when you try to access the property of obj with foo or bar or any other object, you are actually doing
obj["[object Object]"]
You're defining foo as an object, and bar as an object. When you assign them to the original object (obj), you're basically saying this:
obj["Object"] = 'hello';
obj["Object"] = 'hi';
console.log(obj["Object"]); //Will be the last object.
Keys need to be string types. If they're not a string, they will be converted to a string. In the cast of Object() to a string, they'll be turned into [object Object]. Check out this answer for an alternatitve way to override toString()'s functionality to return the object's name, or a unique identifer for the key you're trying to create.
To see this in action, let's do this:
var obj = new Object();
var foo = new Object();
var bar = new Object();
obj[foo] = 'hello';
console.log(obj);
/* Shows:
{
"[object Object]": "hello"
}
*/
obj[bar] = 'hi';
console.log(obj);
/* Shows:
{
"[object Object]": "hi"
}
*/
console.log(obj[foo]); //Will show hi
console.log(obj['[object Object]']); //Essentially the same thing
I have not used the new object constructor on javascript yet, since it is not my preferred language, but the mistake is most likely obvious, you have not assigned anything on your "foo" and "bar" variables, so regardless, their values will be the same, which is the initial value upon declaration of the object without any assignment. What's happening is you are assigning second value on top of your first, which applies to the "obj" array's element.
You are using objects as property-names in your object obj. Property names are strings, therefore your objects are stringified to [object Object]. As both objects are stringified to the same name, bar replaces foo.
The result looks like this:
{
"[object Object]": "hi"
}
I came across this code snippet on Mozilla Developer Network (MDN) and I am racking my brain in trying to figure out why the result would indeed be 'value'
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value';
console.log(object[bar]);
I would be grateful if someone would be so kind as to enlighten me!
object[foo] = 'value';
You can only have strings as identifiers and hence when the above runs, JavaScript internally calls ToString method, which represents "[object Object]". That's how objects are represented.
Now when you do object[bar], bar.toString() is also "[object Object]", and since 'value' is stored with "[object Object]" as key, it gets returned.
If you have a quick look in your console, you will see this is because foo is being coerced into a string (since all keys in Javascript are strings**), which defaults to [object object]. The string [object object] is the same for every object, so foo appears to be bar, but in essence it is not. Check out the below output:
var foo = {unique_prop: 1}, bar = {unique_prop: 2}, object = {};
object[foo] = 'value';
var output = document.getElementById('p')
for(thing in object){
output.textContent += thing + " = " + object[thing];
}
<p id='p'></p>
** I think that ES6 has a way of setting a computed key using {[func]: value} syntax, but I have not looked into this very deeply yet, so excuse me for the possible incorrectness.
You can see what's going on here with 3 mini experiments:
What is the result of toString() called on each of the objects you create?
foo.toString(), bar.toString() and object.toString() will output:
[object Object]
What is the result of object[{}]?
it is also "value", because the key that the runtime used to store your value is literally [object Object]
Let's change the behaviour of toString and see what happens.
Object.prototype.toString = function(){
return this.unique_prop;
};
// Re run the code
object[foo] = "value";
console.log(object[bar]); // Returns undefined
// Value was stored under the key "1"
console.log(object[1]); // Returns "value"
Because the key in this object is a string representation of the foo and bar objects, like
Object {[object Object]: "value"}.
As explained above, setting the object property results with an object stringifys the key
> console.log(foo.toString())
[Log] [object Object]
so object[foo] is equivalent to
object["[object Object]"] = 'value';
However if you actually wanted them to be different you could do something like this:
> console.log(JSON.stringify(foo))
[Log] {"unique_prop":1}
> object[JSON.stringify(foo)] = 'donkey'
> console.log(object)
[Log] {[object Object]: "value", {"unique_prop":1}: "donkey"}
> console.log(object[JSON.stringify(bar)])
[Log] undefined
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)
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/
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.
That is because there are different types of objects in Javascript!
For example
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
...
Object objects!
stringify({}) -> [object Object]
the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
When you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
If you want to see value inside "[Object objects]" use:
console.log(JSON.stringify(result))
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.
Another option is to use JSON.stringify(obj)
For example:
exampleObj = {'a':1,'b':2,'c':3};
alert(JSON.stringify(exampleObj))
https://www.w3schools.com/js/js_json_stringify.asp
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))
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)
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)
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)
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/
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.
That is because there are different types of objects in Javascript!
For example
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
...
Object objects!
stringify({}) -> [object Object]
the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
When you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
If you want to see value inside "[Object objects]" use:
console.log(JSON.stringify(result))
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.
Another option is to use JSON.stringify(obj)
For example:
exampleObj = {'a':1,'b':2,'c':3};
alert(JSON.stringify(exampleObj))
https://www.w3schools.com/js/js_json_stringify.asp
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))
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)
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)