Encountering an unexpected token while using square brackets within an object

Eliminating some important details, I have a series of code that leads to an object with properties labeled as prop. Afterward, I set up a $scope.$watch to monitor the changes in the object. Subsequently, the program broadcasts two pieces of data: prop, which represents the property name, and newValue[prop], indicating the value of that particular property. The process is illustrated below:

$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 data displays via console.log() as

Object {a: (the property's name), b: (the value of the property)}
as expected.

However, if I remove the keys a: and b: like so:

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

An error occurs stating

Uncaught SyntaxError: Unexpected token [
.

It raises the question—Is it not permissible to reference properties using brackets within objects? Can you shed any light on this issue?

Answer №1

{prop, newValue[prop]} does not actually create a property with the name from the prop variable. Instead, it results in an invalid object initializer -- not due to the use of [] ({prop, "foo"} would also fail), but because object initializers do not function in that manner.

...the property name and newValue[prop]

In order to assign a property name from a variable to an object in ES5, you must first instantiate the object, and then add the property:

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

In ES6, you have the option to utilize the new dynamic property name notation:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for retrieving data from an Excel spreadsheet on an HTML/CSS webpage

I have a single HTML template at this location: . The current page is tailored for the state of Arkansas in the US, but I now need to replicate the design for all 50 states. Each state page will have the same layout, but different content specific to that ...

Is there a way to stop TinyMCE from adding CDATA to <script> elements and from commenting out <style> elements?

Setting aside the concerns surrounding allowing <script> content within a Web editor, I am fully aware of them. What I am interested in is permitting <style> and <script> elements within the text content. However, every time I attempt to ...

What is the proper way to incorporate a backend variable within an EJS script block?

<!-- begin snippet: js hide: false console: true babel: false --> <script> // initializing the map var map = L.map('map').setView([25.037393872113785, 121.56372070312499], 12); // loading a tile layer var baseLayer = L ...

Is there a method to programmatically clear cache in an Angular 7 application?

I am facing an issue with my component that lazy loads images. The first time the page loads, the images are displayed using lazy loading. However, if I refresh, reload, or close and reopen the tab, the images are pre-loaded from the cache. Is there a wa ...

In React-Redux, the reducer is programmed to only ever return the initial state

When implementing Redux in my React app, I noticed that the reducer always returned false as the initial state. Thank you for your answer. [UPDATE]: I made the following change: let newState = {...state} However, the reducer still returned false. This ...

Sending the HTML variable to an Angular function

I'm running into an issue where I need to pass a Handlebar HTML variable to a scope function using Angular. If I try passing it as function('{{variable}}'), the function receives the variable literally as "{{variable}}". But if I use functio ...

Using ChartsJs to visualize input data formatted in the German data format

I am relatively new to working with Charts.js, but I will need it to generate some visually appealing graphs for my website. In the background, I have a Django project running that calculates a specific set of numbers for me. Due to the language setting in ...

I can't believe I already have 111 npm downloads!

Just two days back, I released my initial npm package which is a basic library used to trim and merge audio files. You can check it out here. What surprises me is that it has already garnered 111 downloads even though I haven't promoted it or provide ...

Issue with accessing Protractor spec file location

As a newcomer to Protractor, I followed a tutorial on GitHub to set everything up. The tutorial was successful, but when I tried to apply it to my actual code, I encountered a problem. I found that I can only call the spec.js file if it's located in t ...

Organize based on 2 factors, with emphasis on 1

Looking for a way to sort a list of posts by two variables - date (created) and score (score>). The main goal is to prioritize the sorting based on the score, so that the highest scoring posts appear first.</p> <p>To clarify, the desired so ...

Merging HTML Array with jQuery

I am working with input fields of type text in the following code snippet: <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > <input type="text" minlength="1" maxlength="1" class="myinputs" name="myinputs[]" > ...

Issue with Angular Route Guard - Incorrect redirection to login page

I'm encountering an issue with my Angular app where even after the JWT token has expired, I am still able to navigate within the application without any API data being accessible. I've double-checked my setup and it seems right, but for some reas ...

Changing a single state in React results in the modification of both states simultaneously

Whenever I attempt to modify one state, I find that another state is inexplicably changing as well. I've scoured my code for the issue but can't seem to pinpoint it. What steps should I take next? Here's the snippet of code in question: impo ...

Tips for transferring HTML code to a controller

Currently facing an issue while working with MVC and attempting to store HTML code from a view in a database field. In the JS section of my MVC solution, I have the following code snippet: var data = { id_perizia: $("#id_perizia").val(), pinSessione: $("# ...

Whenever I press the button, the table content disappears mysteriously

Objective: The main goal is to hide all the table bodies initially. Upon clicking the arrow button, the respective table body should be displayed. Challenge Faced: Encountering difficulty in hiding the table bodies initially. Additionally, only the last ...

Exploring the process of iterating through a JSON response in PHP to extract all values

{ "ver":2, "inputs":[ { "sequence":4294967295, "witness":"", "prev_out":{ "spent":true, "tx_index":372805487, "type":0, "addr":"3AFgA1pHKrk4jFHwzUL1CKgZvXyFSWZfgD", "value":12712, ...

Indicate the locale identification within the URL

Researching information on this specific topic related to angularJS has proven to be quite challenging. Is there a way for me to specify and rewrite all urls with a locale id, such as en-uk or nl-nl? Furthermore, I am interested in implementing proper ro ...

Node.js - Request timeout issue: Headers cannot be set after they have already been sent

My node.js app is running with mongoose, express, mongodb. I have a 'team' page that displays teams from the database. Everything was working fine until I added the code below. Now, when I navigate to the page and refresh it or try to load it aga ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

Issue [ERR_HTTP HEADERS_SENT]: Inability to change headers once they have been sent to the client in a Node.js environment

When accessing the following URL - http://localhost:3080/api/msgs/[email protected], I am expecting to retrieve all user commits. However, I am only retrieving one user commit and encountering the error [Error [ERR_HTTP_HEADERS_SENT]: Cannot set heade ...