Object.getPrototypeOf(o) method issue - javascript

I struggle to understand Object.getPrototypeOf(o). I'm playing with that method in below code.
var obj0 = {x: 10};
var obj1 = Object.create(null, {
'name': {value: 'first object name', enumerable: false},
});
var obj2 = Object.create(obj1, {
'location': {value: 'second object location'},
});
alert(Object.getPrototypeOf(obj0)); // [object Object]
alert(Object.getPrototypeOf(obj1)); // null
alert(Object.getPrototypeOf(obj2)); // TypeError: Cannot convert object to primitive value
I would appreciate any hint on:
1/ Why object2 returns TypeError?
2/ Is Object.getPrototypeOf method always returns [object Object] as the "highest object" in prototype chain? I would assume that it will give me it's "nearest" object in chain so ex. if there would be obj3 that has obj0 as prototype it would give me [obj0 Object] instead of [object Object].

This is simply a problem with using alert, which converts the alerted object to a String. [object Object] is the string representation of {}:
({foo: 'bar'}).toString(); // [object Object]
You should use the console for your testing, which will show you a better representation of the object (see example on JSFiddle).
Also in the example is a new object, obj3, which shows that Object.getPrototypeOf() does return the nearest object, not the root prototype.

Related

Get the Object name in JavaScript

I have a simple object called "obj1".
let obj1 = {
x: 1,
y: 5,
meth: function() {
return `The result of the ${this} is ${this.x+this.y}`;
}
};
in console, it print
The result of the [object Object] is 6;
I want to get the Object name, which is obj1 but it gives me [object Object].
I tried this.name but it's showing undefined.
I want to get the Object name, which is "obj1"
No, it isn't. Objects don't have names. Your variable's name is obj1, but the object's isn't.
There is no practical way for obj1.meth to know the name of that variable (other than the programmer hardcoding it, since of course the programmer knows the name). That information just isn't provided to meth. Note that it would be context-sensitive information:
let obj1 = { /*...*/ };
let obj2 = obj1;
obj2.meth(); // Should say...what? "obj1"? "obj2"?
// (doesn't matter, it can't say either)

JavaScript object array

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"
}

Understanding Javascript Object Code Snippet

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

need to return an array of records but javascript returns object object [duplicate]

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)

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 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)

Categories

Resources