14

I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'

6 Answers 6

42

You can't use variables in dot notation (short of using eval, which you don't want to do). With dot notation the property name is essentially a constant.

myObj.propName
// is equivalent to
myObj["propName"]
Sign up to request clarification or add additional context in comments.

8 Comments

-1 as it's wrong. see my answer. propName in the first line is treated as a property, not a variable!
@sjngm I disagree. @nnnnnn is not implying that propName is a variable, but rather the name of a property.
@zack Well, then a different name would have been better. It says "is equivalent to" meaning the first line does the same thing as the third line. And that is not true.
@zack Maybe I'm wrong, but the first time I read that answer it said myObj[propName]. No? Other than that I agree, it's the same. Now.
@Paul Sham In that case you may want to try jshint.com instead. I've wrestled with JSLint for a while and sometimes I just plainly disagree with its ramblings. I'm a big fan of Crockford, but JSLint is pretty restrictive.
|
9

The short answer is: you can't access a property using dot notation unless you know the property's name.

Dot notation also puts a restriction on the property names you can access because the property name must be a valid JavaScript identifier. For example, if you had a property called my prop (or better yet, my%prop) then it would not be possible to access it without using bracket notation because it would lead to a syntax error is most cases.

The Member Operators page on MDN explains this a bit further.

As an aside:

Wouldn't it be a little confusing to be able to dynamically look up properties using dot notation?

item.x // is this the property "x" or do I have to look up variable "x"?

1 Comment

Thanks for the links to references. And yes, now that I think about it, it would be confusing. I just didn't know if there was a way.
7

If you use numbers to access an array you have to use the brackets:

item[0]

var k = 0;
item[k]

as

item.0

doesn't work (wrong syntax).

If you use a string

item["key"]

var p = "key";
item[p]

equals

item.key

In the latter context

var p = "key";
item.p

would cause a wrong output as p is not treated as a variable here.

1 Comment

Thanks, I wasn't specifically asking about a number, I just didn't think of a better identifier. But, this is good information to also know about numbers.
4

You actually can now.

In this case you can use square brackets to use a variable for dot notation.

console.log(item.[x])

This is especially useful for use in Typescript.

Comments

3

the dot notation is limited to certain chars ... see this question ... the square bracket notation allows you to break that limitation:

var item = {};
item['very long variable name containing empty spaces ... and dots...'] = 'valid var';
item.1 = 'not valid var'; // will not work;
item['1'] = 'valid var'; // will do just fine...

Comments

2

I made a function to set variables by dot notation, in angular 2, but this could also be used in vanilla javascript, with minor modifications.

class Utility {
    static setByDot(_obj, _path, _val) {
        return _path.split('.').reduce(function (prev, curr, _idx, _arr) {
            if ( _idx == (_arr.length-1) && prev ) {
                prev[curr] = _val;
            }

            return prev ? prev[curr] : null
        }, _obj || self);
    }
}

So you can just call

Utility.setByDot( _obj, 'foo.bar', 'value' );

And then

console.log( _obj.foo.bar );

Output, if path existed

string(6) 'value' 

If path doesnt exist, it just exits gracefully.

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.