Encountering an Unexpected Token Error while attempting to utilize array elements as keys within an object

Encountering a perplexing issue, as the JavaScript code provided below generates an Unexpected Token error in Chrome:

var somearray = ["foo","bar"];
var someassoc = {somearray[0]:somearray[1]};

The specific error message displayed is:

Uncaught SyntaxError: Unexpected token [

One would anticipate that the code should simply create an object where somearray[0] serves as the key and somearray[1] acts as the corresponding value.

Hence, why does this error occur? Typically, an Unexpected Token signifies misplacement of brackets or similar issues, but such mistakes are not evident in this scenario.

Answer №1

To use a key in a JavaScript object literal, it should be either a static key or an expression enclosed in square brackets `[]` (this requires ES2015 support).

The issue with your code is that the key `somearray[0]` is not valid.

If you want to rewrite it using ES5, you can do it like this:

var somearray = ["foo", "bar"];
var someassoc = {};
someassoc[somearray[0]] = somearray[1];

For ES2015, you would use:

var somearray = ["foo", "bar"];
var someassoc = { [somearray[0]]: somearray[1]};

Refer to these sections of the standard for more information:

In essence, the key must be a valid identifier.

Answer №2

When working with JavaScript and declaring objects, it's important to remember that the key name should always be a simple string. For example:

var object = {'key': 'Hello World'};

However, if you need to use a dynamic key name, such as somearray[0], you can simply declare someassoc as an object:

var someassoc = {};

Then, you can set up a key-value pair by doing either of the following:

someassoc.key = 'Hello World';

OR

someassoc['key'] = 'Hello World';

In your case, it would look like this:

someassoc[somearray[0]] = somearray[1];

That covers it! :)

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

Yet another instance of an ASP.net AJAX SYS Undefined Error

I am facing a challenging situation with my ASP.net 2.0 Web Project developed in VS 2008. The issue is occurring on my development XP system as well as our Windows 2000 and 2008 servers. The project utilizes AJAX 1 and makes references to System.Web.Extens ...

The magic of React.js in creating fluid scrolling single page applications

Embarking on my journey with react.js, my aim is to develop a single page application where the top navigation links smoothly scroll to the relevant sections on the front page akin to THIS SITE. Currently, my application utilizes React.js and React-Router ...

Saving similar and dissimilar information in a database

I have been working on implementing a Like and Unlike feature for users to interact with products. Following this tutorial at , I've completed the necessary steps. However, I'm facing an issue where the likes are not being stored in the database ...

Modify and store Json using php

I've been attempting to modify a JSON file by removing the part of the string after the dot from items in the 'Merchant' key. Essentially, I want to convert "Amazon.com" to simply "Amazon". Below is the code I am using: $file = 'myfil ...

Encountering an Issue: Unable to successfully transform JavaScript argument argument 0 [nsIDOMWindow.getComputedStyle]

I have created a piece of javascript code that is meant to replace text with an image and then adjust the size of the new image based on the font size of the original text. Unfortunately, I am encountering an error message that reads: Could not convert Ja ...

What is the best way to retrieve the results of multiple HTTP requests in my specific case?

Currently, I am facing an issue while attempting to execute an HTTP request and then store the output into my array. This is what I have so far: Ctrl for (var i=0; i < numOfProduct.length; i++) { productFactory.makeRequest(numOfProduct[i].id) ...

Reorganizing the index of a numpy array

Looking to convert a 2D array into an image using NumPy. My goal is to transform the 'image' array with dimensions of 140x120 into a 3D array of 140x120x3 by stacking the same array 3 times for a grayscale image to be used with skimage. My attem ...

Enhance your Vue app by incorporating animate effects or classes when entering a div

Currently, I am working on a Vue project and I am looking to implement an effect or add a class to a specific div when the user scrolls to it. This functionality is similar to what can be achieved with ScrollReveal. Has anyone encountered this scenario be ...

Error encountered in Next.JS when calling getInitialProps(ctx) due to undefined ctx variable

This is my code import NavLayout from "../../components/Navigation/Navigation"; export default function WorldOfWarcraft({ game }) { return (<NavLayout> {game.link} </NavLayout>) } WorldOfWarcraft.getInitialProps = as ...

Leveraging data generated by a CasperJS script within an AngularJS application

After using yeoman.io to create an angular.js single page application, I found myself with app.js managing routes, mycontroller.js scripts, and an index.html file filled with "bower_components" references for libraries installed through the command line us ...

Dealing with errors in Express JS following the response

In my quest to implement effective error handling in Express, I experimented with various techniques. Initially, I relied on process.on('uncaughtException') but soon realized it was not a recommended practice. Next, I turned to the "Domain" featu ...

Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately ...

Find the tiniest array within a collection of arrays

Looking at an array filled with various arrays, I am aiming to pinpoint the shortest path available within the paths array. paths = [ ["LEFT", "RIGHT", "RIGHT", "BOTTOM", "TOP"], ["RIGHT", "LEFT", "TOP"], ["TOP", "LEFT"] ]; paths.map((path)=& ...

Is it possible to make asynchronous calls to an external API without causing any drag on the overall speed of the website?

Currently, I operate an online store where at the end of the page, I integrate the eBay API with items related to the main product. Unfortunately, I have noticed that this integration causes a significant delay in the overall page loading by 4 to 10 secon ...

Arranging object arrays according to strings

Imagine there is an array: var a = [ { name: 'Tom', surname: 'TestAsIvanov' }, { name: 'Kate', surname: 'Ivanova' }, { name: 'John', surname: 'Alivanov' }, { name: 'Ivan&apos ...

Sort activities according to the preferences of the user

This is the concept behind my current design. Click here to view the design When making a GET request, I retrieve data from a MongoDB database and display it on the view. Now, I aim to implement a filter functionality based on user input through a form. ...

Ensure the Firebase real-time database in Javascript purges the active session upon tab or browser closure

I need to implement a feature in my Firebase real-time database project using JavaScript where the current session is logged out automatically after closing the tab or browser. When I log in with my email and password, if I copy the URL and paste it into ...

Utilize a custom function on dynamically generated elements

I am utilizing the following jQuery function: $("#agenda_image_1,#agenda_image_2,#agenda_image_3").PictureCut({ InputOfImageDirectory : "image", PluginFolderOnServer : "../xxx/modules/xxx/assets/js/jQuery-Picture-Cut-master/", Fol ...

Values in C array mysteriously alter without any clear intervention

I am currently working on code that converts a matrix into a unique vector. The process involves certain conditions for the elements added to the vector, so I begin by running a test to determine the number of elements from each column that will be include ...

Execute a function on every cell within a column of a table using jQuery

In the code snippet below, I have defined a table element as $table. My goal is to iterate through every cell in a specific column that is identified by a particular table heading - qc_statusTh. I've managed to locate the index of this table heading ( ...