0

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]
2
  • myObj[place1] won't work unless there is an initialized variable named place1 Commented Jun 23, 2016 at 11:15
  • 1
    Second one should be myObj["place1"]. It is notation how you want to use it. Commented Jun 23, 2016 at 11:17

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

please write me the syntax using my code, how do i access place2?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.