Paul Sham
Paul Sham

Reputation: 3205

How to use variables in dot notation like square bracket notation

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'

Upvotes: 14

Views: 54242

Answers (6)

dwalter
dwalter

Reputation: 111

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.

Upvotes: 4

Karl Johan Vallner
Karl Johan Vallner

Reputation: 4300

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.

Upvotes: 2

Zack The Human
Zack The Human

Reputation: 8481

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

Upvotes: 9

Alex Pacurar
Alex Pacurar

Reputation: 5861

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...

Upvotes: 3

sjngm
sjngm

Reputation: 12861

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.

Upvotes: 7

nnnnnn
nnnnnn

Reputation: 150030

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

Upvotes: 42

Related Questions