what is a difference myObj.a=b vs myObj[a]=b [duplicate] - javascript

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
I was reading here on stack overflow that these are not equal. So what is the difference.
What happened is that in 2nd case value was assigned as the property of myObj. So if b='abc';
then myObj.abc was now available.
I had always thought same thing but [] version was used when name were weird ones.

Dot notation takes an identifier that is the property name. The square bracket notation accepts a string representation of the property name.
Given var a = "a"; then myObj.a = b and myObj[a] = b and myObj["a"] = b are equivalent.

The difference between myObj.a=b and myObj[a]=b is that in the first case you are accessing an attribute called a in the object. In the second you are accessing an attribute whose name is in a variable called a.
On the other hand, myObj.a=b and myObj["a"]=b would be equivalent.

a lot, results would depends on a var value. but ["a"] would be the same as .a

Related

the way of accessing the number element of object in javascript in '.' causes an error [duplicate]

This question already has answers here:
Object property name as number
(6 answers)
How can I access object properties containing special characters?
(2 answers)
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 1 year ago.
First, I am a beginner of javascript.
Please understand asking this simple question.. (looks simple)
I was making a membership related webpage and encountered an error..
I was learned that to access the element of an object, I can use '.'(dot)
so I coded like,
It was a bit long object(json type contents) but.. to sum up,
dict1 = {'a':1, 'b':2, 'c':3};
dict2 = {1:'a', 2:'b', 3:'c'}
dict1.a
result: 1
dict2.1
result: Uncaught SyntaxError: Unexpected number
so the point is,
Someone may think, "if you can see the elements, why would you access the element by '.'(dot). if you already know it can cause the error."
but the data is user input and users can input any data as they wish.
Javascript provides '.'(dot) operator for Object but not working for number Element??
or do I use the dot in wrong way?
If you use dot notation, your key must be a valid identifier (start with a letter, $ or _). So in this case you would need to use dict2['1'].
You can do something like this to get the values
// With the braces you can get the values even if the key is a number
let dict2 = {
1: 'a',
2: 'b',
3: 'c'
}
console.log(dict2[1])
// Even if you want to access the values that are having keys like strings you can use the same operator
dict1 = {'a':1, 'b':2, 'c':3};
console.log(dict1['a'])

Targeting an array of objects in JavaScript [duplicate]

This question already has answers here:
Unable to access JSON property with "-" dash [duplicate]
(5 answers)
How can I access object properties containing special characters?
(2 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I have a value in this format:
var state = [{"industry-type":"football","your-role":"coach"}]
I would like to output "football". How can I do this?
I've tried state[0].industry-type but it returns an error:
Uncaught ReferenceError: type is not defined
Any help appreciated.
It does not like the '-' in your property name, try:
state[0]['industry-type']
This happens because you can't access a property with - directly.
var state = [{"industry-type":"football","your-role":"coach"}];
console.log(state[0]['industry-type']);
The - symbol is reserved in Javascript, you cannot use it to refer to an object's property because Javascript thinks you're trying to do subtraction: state[0].industry - type; Hence the error "Uncaught ReferenceError: type is not defined" - it is looking for a variable named type to subtract with, which it can't find.
Instead, refer to it by:
state[0]['industry-type']
Because in Javascript, object.property and object['property'] are equal.
For what it's worth, if you have control over those names, it is best practice in Javascript to name things with Camel Case, so your variable would be defined as:
var state = [{"industryType":"football","yourRole":"coach"}]
Then, you could access it like:
state[0].industryType
In order to be able to use dot notation then your:
...property must be a valid JavaScript identifier, i.e. a sequence of
alphanumerical characters, also including the underscore ("_") and
dollar sign ("$"), that cannot start with a number.
From MDN
Like the other answers pointed out, you have to use square bracket notation to access property names of an object that are not valid JavaScript identifiers.
e.g.
state[0]["industry-type"]
Related SO question:
What characters are valid for JavaScript variable names?
You'll need to use bracket notation for the attribute -
state[0]['industry-type']

Difference in referencing an object using object.key = value and object['key'] = value [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 6 years ago.
What is the difference between referencing an object with object.key = value and object['key'] = value For example if I had an object call var myObj = {};
I believe the quote notation allows for arbitrary keys, (like console.log({' 1a':3}[' 1a']), whereas the dot syntax can only be used with keys that begin with a letter.

Why I can't access JSON dictionary element using dot notation? [duplicate]

This question already has answers here:
Object property name as number
(6 answers)
Closed 6 years ago.
I have a following JSON representation:
var collectionCopy = JSON.parse(JSON.stringify(
{
1 : {
2: "2"
}
}
));
Why cant I access key "2" using dot notation (i.e. collectionCopy.1.2) ?
You can use the dot notation for accessing an object's properties only on a valid identifiers in the language.
And since numbers (or anything that starts with a number) are not a valid identifiers you can access it (as a property of an object) only with the bracket notation.
This is because the keys are strings not actual numbers:
to access it use:
collectionCopy[1][2]
or
collectionCopy['1']['2']
Relevant docs on accessing properties

need help in javascript understanding a line [duplicate]

This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Closed 8 years ago.
var stooge = {
"first-name": "Jerome",
"last-name": "Howard"
};
var properties = [
'first-name',
'middle-name',
'last-name',
'profession'];
for (i = 0; i < properties.length; i++) {
console.log(properties[i] + ': ' + stooge[properties[i]]);
}
I don't understand stooge[properties[i]]. Why are we using bracket before properties?
Can someone explain when to use brackets?
I dont understand stooge[properties[i]].
It means more or less literally what it says.
If i is 0, then properties[i] is properties[0], which is set to 'first-name'.
Therefore, stooge[properties[i]] is stooge[properties[0]] is stooge['first-name'] is "Jerome".
EDIT
As someone pointed out, you cannot use dot-notation here. The name of the property is first-name. If you typed stooge.first-name, the parser would interpret that as stooge.first - name. undefined minus undefined is... NaN!
This is just a way to access properties dynamically from an object. In this cause since there is an array of strings, it lets you get the value from the object. Since you can't do something like obj.'some-string'
This might help JavaScript property access: dot notation vs. brackets?
Object properties can be accessed with a .. or with [].
But dot notation won't work here.
because if you switch stooge[properties[i]] to stooge.properties[i] it would return undefined, because the stooge object doesn't have a member named properties.

Categories

Resources