Get the Object name in JavaScript - 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)

Related

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

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)

Dynamic object name property not working

I have a function through which I pass some variables as arguments. I need some of those to become variable names or object property names.
key(500, 'door', 10, 'bounceOut', 'regY', -150, 5, 'bounceIn');
function key(point, instance, speed, ease, prop, value, speed2, ease2, prop2, value2){
ani.instance = true;
createjs.Tween.get(instance, {override: true}).to({prop: value}, -(value + -instance.prop) * speed, createjs.Ease.ease);
}
The solution stated here should have worked, but it does nothing for me.
// ani.instance changed to:
ani[instance]; // no error here
// instance.prop changed to:
instance[prop]; // returns 'undefined', expected it to return 'door[regY]'. instance and prop return 'door' and 'regY' respectively though
What is going on here? Can anyone nudge me in the right direction? Thank you :)
EDIT
What I want the code to read is:
door.regY = 200;
createjs.Tween.get(door, {override: true}).to({regY: -150}, -(-150 + -door.regY) * 10, createjs.Ease.bounceOut);
In ES5 , You can only create or fetch "dynamic properties" on an object . So you need an object , or use this.
with the [] notation.
var prop = "something";
this[prop] ="my value";
//this.something=== "my value"
var obj = {};
obj[prop] = "a value";
// obj.something === "a value";
var obj1 = {prop:"value"}
// will not make obj.something === "value"
// but obj.prop==="value" because in this case prop cannot be a variable
so you need to do something like that :
var arg1 = {};
arg1[prop]=value2;
var arg2 = {}
arg2[prop] = value2;
createjs.Tween.get(instance, arg1).to(arg2, -(value2 + -door[prop]) * 10, createjs.Ease.ease);
and so on , you need to define the objects before passing them to createjs.Tween.get method.
instance probably needs to be an object and not a string but since i know neither createJS or your script i cant tell.
EDIT : read this : http://www.jibbering.com/faq/faq_notes/square_brackets.html
In the invokation of your key function, you're passing a string as the instance argument.
Thus, you will be able to access properties of the string, not your door object.
I assume there's a door object since you probably have such an object somewhere else, which has the property you're trying to access inside key (regY in your example). You should be calling key like this, then:
key(500, door, 10, 'bounceOut', 'regY', -150, 5, 'bounceIn');
where door is a variable referencing that other object. Of course, you wouldn't know the variable name inside key then. If you also need that, you'll need to pass it as a different parameter. However, it doesn't sound like a good decision, do you actually need it?

how to declare an associative array in javascript? Unlike PHP, I find it really difficult to implement

How do you access a key named "foo" of the 5th element of an array that is the 2nd element of another array that is the value of a hash key named "baz"?
can you provide the basic examples?
You want to use an object:
var obj = {
foo: {
bar: "yo"
}
}
console.log(obj["foo"]["bar"]);
// Or you could do this
var obj = {};
obj["foo"] = {};
obj["foo"]["bar"] = "yo";
console.log(obj["foo"]["bar"]);
Note the order of an object is not guaranteed and can change depending on the interpreter / compiler.
An array in JavaScript is just an object with numerical indices (With some specific methods - see comment below). In fact pretty much everything in JavaScript is an object.
How do you access a key named "foo" of the 5th element of an array
that is the 2nd element of another array that is the value of a hash
key named "baz"?
variableName["baz"][1][4]["foo"];
Would get you "The value here" from
var variableName = { baz: [0, [0, 1, 2, 3, { foo: "The value here" }]] };
and here's a jsFiddle to play with

__hash__ for javascript?

Is there a way to give objects in js custom hashes, just as overriding
__hash__()
in python let's someone define how a given object is hashed into a dictionary.
My underlying question is: what hash function is used to put js objects into associative arrays, and can I over-ride it?
You mean using objects as keys, how do you make sure you access that key again?
The magic method is toString(). Turns out all objects in JS use string keys, and the toString() method is called if it's not a string.
http://jsfiddle.net/udsdT/1/
var objA = {
data: 'yay',
toString: function() {
return 'value_as_key';
}
};
var objB = {
data: 'some other totally data thing',
toString: function() {
return 'value_as_key';
}
}
var foo = {};
foo[objA] = 'abc';
foo[objB] = 'def';
foo['value_as_key'] = 'qwe';
foo.value_as_key = 'omg';
foo[objA]; // 'omg'
foo[objB]; // 'omg'
foo['value_as_key']; // 'omg'
foo.value_as_key; // 'omg'
​​​​​​Usually though, you really don't want to use whole objects as keys. Especially if you dont create your own toString() method, since the default toString() method on basic objects isn't exactly very awesome...
({a:123}).toString() // [object Object]
({b:456}).toString() // [object Object]
var foo = {};
foo[{a:123}] = 'wtf';
foo[{asdf:9876}]; // 'wtf'
foo['[object Object]']; // 'wtf
In JS, you can't control the hashing, but you don't have to.
Two things are the same if they're equal. The hash is not part of the definition, it's just an implementation detail. Under the covers, two different objects may have the same hash, but they're still different, and the implementation has to deal with that magically (e.g., by using a chaining hash table).
Also, the keys of an object are always strings—the interpreter will stringify the values inside the hash constructor, inside the [], or after the ., rather than storing the actual values, which means that this rarely comes up in the first place.
To give some examples:
function X() {}
x = new X()
y = new Y()
h = {x: 2, y: 3} // h has 2 members, named "x" and "y"
a = (x, y)
b = (x, y)
h[a] = 4
h[b] = 5 // h has 3 members, named "x", "y", and "[object Object]"
Put in Python terms, it's as if dict called __repr__ on keys instead of __hash__ (although this isn't quite 100% accurate), which means you can provide a custom toString method to control equal-ness of different instances of your class.

Categories

Resources