nikk wong
nikk wong

Reputation: 8670

Using square brackets inside an object: Unexpected Token

I'm leaving out a bunch of context, but I don't think a lot of it is necessary. I have a bunch of code leading up to an object with prop properties. I'm then setting up a $scope.$watch which is watching the object, and then, essentially, broadcasting prop—the name of the property, and newValue[prop], the value of that property. It looks a bit like this:

$scope.$watch(function(){return object;}, function(newValue, oldValue) {
    for (var prop in object) {
        if (newValue[prop] !== oldValue[prop]) {
            $scope.$broadcast('from-parent', {a: prop, b: newValue[prop]});
        }
    }
};

The broadcasted message console.log()'s out Object {a: (the property's name), b: (the value of the property)} as you would expect.

Strangely though, when I remove out the a: and b: keys, i.e.

$scope.$broadcast('from-parent', {prop, newValue[prop]});

I get a Uncaught SyntaxError: Unexpected token [ error.

Are you not allowed to refer to properties via brackets in objects? What's going on here?

Upvotes: 2

Views: 1176

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074198

{prop, newValue[prop]} won't create a property with the name from the prop variable, it just ends up being an invalid object initializer — not because of the [] ({prop, "foo"} would also have failed), but because object initializers don't work that way.

...the name of the property, and newValue[prop]

To give an object a property name from a variable, in ES5 you have to first create the object, then add the property:

var obj = {};
obj[prop] = newValue[prop];
$scope.$broadcast('from-parent', obj);

In ES6, you'll be able to use the new dynamic property name notation instead:

// REQUIRES ES6!
$scope.$broadcast('from-parent', {[prop]: newValue[prop]});

Upvotes: 2

Related Questions