We create an object in javascript...
var myObj = {
name1: 'abc',
place1: 'xyz',
name2: 'mno',
place2: 'uvw',
};
Now when we try to access place1, how should we do it?
myObj.place1 or myObj[place1]
myObj.place1 will work directly,
myObj["place1"] will also work directly.
but if you want to use myObj[place1]... here place1 is treated as a value from variable to make this work use..
var myObj = {
name1: 'abc',
place1: 'xyz',
name2: 'mno',
place2: 'uvw',
};
var Place1 = "place1";
myObj[Place1]
we use "." dot notation when we want to access the value of the js object via property
There are scenarios where you cannot use the "object-dot-attribute": For example:
var obj={
"hello world": 1,
"hello-world":2
}
obj.hello world //syntax error
obj.hello-world //this is understood as (obj.hello) - world, a subtraction
So the only way to get these attributes is using
obj["hello world"]
obj["hello-world"]
In general using the dot is safer because any IDE can check if the attribute is already created and can infer if the type is correct, so my recommendation is to use the object-dot-notation unless you can't.
Another scenario where you cannot use it is when you don't know the name of the attribute, for example is you are using the object as a map:
var map={};
function addUser(username,userId) {
map[userId]=username;
}
function getUserName(userId) {
return map[userId]
}
Getting back to your example:
var myObj = {
name1: 'abc',
place1: 'xyz',
name2: 'mno',
place2: 'uvw',
};
The recommended way to get the value is:
myObj.place2
But you can use
myObj["place2"]
You can Use Dot notation as long as it follows below rule:
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. For example, object.$1 is valid, while object.1 is not.
You can also use a number for key. But make sure that you are using bracket Notation as in object[1] instead of object.1(this will throw an error).
http://javascriptissexy.com/javascript-objects-in-detail/
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors
myObj[place1]won't work unless there is an initialized variable namedplace1