Javascript syntax clear up [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 years ago.
var me = new Object();
me.name = "Adithya";
me.age = 15;
for(var prop in me){
console.log(me.prop);
}
When I run this, it prints undefined. I don't understand why it doesnt print the value. When I type
console.log(prop);
it prints
name
age
Doesn't that mean that prop is a a field in me? So shouldn't me.prop(when prop is name) , work like me.name ?

prop is a variable containing a string so you need to use me[prop] like this:
for(var prop in me){
console.log(me[prop]);
}
When your property name is in a variable, you need to use the [prop] syntax which in your case would be me[prop].
FYI, me.prop tries to access a property named "prop". It does not use the contents of the variable prop. You can only use the dot syntax to access a property when the property name is a constant that is known at code parse time and when the characters in the property are legal to use in the Javascript dot syntax. If it's in a variable (or if it contains characters like a . or a space), then you must use the bracket syntax which will fetch the contents of the variable and use that property name.

The syntax you're looking for is me[prop];
me.prop is equivalent to me['prop'] which is not what you want.
notice you didn't assign a value to name or age before when you did me.age and me.name.

Related

How can I use a key value as a variable name in JavaScript? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 6 years ago.
I want to be able to take JSON into my program and then create objects based off of that data. So, I want to create objects where the name of that object is the value stored in a key value pair. For instance, if I had the following JSON (and I know this isn't perfect JSON):
{
"objectName" : "**variableName**",
"someDataName" : "thatData",
"someOtherDataName" : "thisData"
}
Then I want to be able to make an object like this:
function myObject(thatData, thisData) {
this.name = name;
this.thatData = thatData;
}
var **variableName** = new myObject(thatData, thisData);
The key here is that I want to be able to use the value stored in the ObjectName key value pair as the variable name for the object. Is this even possible? I have been looking for how to do this for a while now. I believe that this is different than "Variable" variables in Javascript? because I am trying to use a value in a key value pair to name my objects.
If I understand correctly what you're trying to do here, one approach may be to set properties within a variable:
let myContainer = {};
// ...
myContainer['whatever_variable_name'] = new ...
You can how use myContainer.whatever_variable_name or myContainer['whatever_variable_name'] to access the new object.
To assign properties from JSON objects, see Object.assign.
You can use the property accessor on the window object to set the value for a dynamic key on the global scope.
var window["**variableName**"] = new myObject(thatData, thisData);

Get value of object inside a for loop with dynamic variable [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
I'm trying to get a value of property (or more) that user provides inside a for loop.
OBJECT:
RULES: {
"required": /.+/,
"numeric": /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/
}
FOR LOOP:
$("input").keyup(function() {
var inputVal = $(this).val();
var rules = $(this).data('rules').split(" ");
for (var i = 0; i < rules.length; i++) {
console.log(rules[i]); // OK - return "required" and "numeric"
console.log(RULES.required); // OK - return "/.+/"
console.log(RULES.rules[i]); // NOT OK
};
});
MARKUP
<input data-rules="required numeric" type="text">
The problem is that it provokes an error: "Cannot read property '0' of undefined".
So how can I look for the value of "rule[i]" and not "rule[i]" itself?
Why does not translate by itself?
Thank you in advance.
you are doing:
RULES.rules[i]
you should do:
RULES[rules[i]]
when you do the first one, Javascript first looks for a rules property on the RULES object (but this property doesn't exist) then it tries to access element 0 of the rules property, which doesn't exist... hence you get "Cannot read property '0' of undefined" error
in the case where you want to access the property of an object using a variable for the name you cannot use dot notation any more and must use the square brackets

Do 'variables' have properties? [duplicate]

This question already has answers here:
Why can't I add properties to a string object in javascript?
(2 answers)
Closed 9 years ago.
Do variables have properties?
The obvious answer should be NO. If I try to assign a property to a variable, it should give an error. Right?
If I do something like:
var someVariable = 'Cat';
someVariable.eyes = 'two'; //Gives no error!
alert(someVariable.eyes); // alerts 'undefined' instead of giving an error!
Variables don't have properties, but their values do. (If the value's an object, anyway.)
In this case, you're trying to set the eyes property of the string currently referenced by someVariable.
It won't work in this case, though. Since primitive values don't have properties, JS will convert the primitive string value into an object and set the property on that object, which pretty much immediately gets silently discarded. The end result: the primitive string remains unmodified.
"Variables" don't actually exist (except strictly within the definition of a scope), only objects. And string objects can't have arbitrary properties assigned by default.

Adding custom variables to an object [duplicate]

This question already has answers here:
How to convert string as object's field name in javascript
(5 answers)
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
Suppose I have an object obj which has some variables in it. What I want to do is to add a new variable which has a name i gave as a parameter.
For example:
var obj=
{
number:8
}
function AddField(field_name,obj)
{
//some magical code here
}
If I call
AddField('name',obj);
i want to be able to do
obj.name='Apple'
after calling this function.
Any ideas?
Use square brackets notation:
obj[field_name] = value;
REF: http://www.jibbering.com/faq/faq_notes/square_brackets.html#vId
Use the bracket notation:
obj[field_name] = void 0;
This creates a new property with an undefined value.
If obj is already defined, you can just do obj.field_name = null or obj["field_name"] = null.
I wouldn't set any value to undefined even though the language allows for that, simply for a semantic issue: undefined means "this property/variable has not been defined" and null means "this property/variable has no value".

How to access a dynamic property: objectName.{variable} [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
jquery dynamic id
(4 answers)
Closed 8 years ago.
i need to access
objectName.myID
but the "myID" part is dynamically generated..
how do i do this?
i tried
this['objectName.'+ variable]
i'd hate to use eval...
ps
this happens in a function (local scope) by the way..
You can access Object properties in two ways:
o.propertyname
//or
o.["propertyname"]
When using the bracket notation you have to put the propertyname in quotes or else it will be interpreted as a variable name (which in your case is exactly what you want). So in your case where you have stored the name of the property as a string, the way to go would be:
var variable = "propertyname";
o[variable];
/* /\ variable is replace with it's string representation "propertyname" */
You can even call methods this way:
var o = {};
var functionname = 'toString';
o[functionname]();
You can mix both notations, your example would look like:
var obj = 'objectName';
var prop = 'myID';
this[obj][prop]
// or this is possible too:
this.objectName[prop]
Assuming propertyName is the name of a variable holding the name of the property, for example 'myId', then you can use.
objectName[propertyName]
More details in the MDN : Working with objects

Categories