Capable of generating a string-keyed map that results in an "Unexpected number error" when the key is referenced

Take a look at the following code snippet:

var arr = [{"id":"123", "name":"Jyotirmoy"}];
var mapObj = {};
for(var  i=0; i < arr.length; i++){mapObj[arr[i].id] = arr[i];}

After creating the map, attempting to access it using the key 'mapObj.123' results in an "Unexpected number" error. However, if you try 'mapObj[123]' or 'mapObj["123"]', the correct object is displayed. What modifications are needed to reference it using the '.' notation?

Answer №1

In Javascript, it is important to note that properties accessed using dot notation (a.x) cannot start with a numeral.

For instance, in the case of the object:

{ one1: foo }

The correct way to access the property would be:

mapObj.one1

However, if the values are numeric as in the id, you must use bracket notation instead (a[x]):

mapObj[1]

or

mapObj["1"]

Answer №2

Is there a way to reference the same using the '.' notation?

Unfortunately, in this scenario, you cannot.

When utilizing the period notation, the property name must adhere to the rules of being a valid identifier:

In JavaScript, identifiers can only consist of alphanumeric characters (along with "$" or "_"), and must not initiate with a numerical digit.

Hence, when attempting to access a numeric key like 123, it is necessary to utilize the bracket notation:

myObj[123]

If your preference leans towards employing dot notation, incorporating an alphabetical prefix to the keys would enable its application:

var arr = [{"id":"123", "name":"Alice"}];
var mapObj = {};

for(var i=0; i < arr.length; i++){
  mapObj['id_' + arr[i].id] = arr[i];
}

console.log(myObj.id_123);

Answer №3

Modify

var array = [{"id":"123", "name":"Jyotirmoy"}];

Into

var array = {"id":"123", "name":"Jyotirmoy"};

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

Initializing start scripts in the package.json file

When launching my react app locally, I need to execute three commands: cd react-web npm run postinstall export REACT_APP_CUSTOMER_ENVIRONMENT=xxx npm start After running these commands, the application server starts on localhost:3000. For the start script ...

I am facing an issue with properly linking my jQuery

After searching through numerous posts on this website, I have yet to find a solution to my problem. My issue involves trying to implement a simple jQuery function that is not functioning as expected. It appears that the jQuery link may not be properly set ...

Distinguishing Features of HTML, Canvas, and WebGL

Is there a way to draw images in WebGL with the same quality as HTML, even when downscaled? I've noticed that scaling down images in WebGL results in poor quality compared to HTML. After reading about 'Handling High DPI (Retina) displays in WebGL ...

Selenium Webdriver failing to select menuitem using text, xpath, or ID

Currently, I have some HTML code embedded in a SharePoint page that appears as follows: <span style="display:none"> <menu type='ServerMenu' id="zz28_RptControls" largeIconMode="true"> <ie:menuitem id="zz29_AddColumn" type="optio ...

Show temporary information on the user's side in a table

To better explain the issue, please refer to the accompanying image. I am working with a Master/Detail form, specifically a Bill of Materials, which involves storing data in two separate database tables. The top portion of the form (Product, Quantity) is ...

Using jQuery to dynamically load custom post type data in WordPress upon clicking

Let me explain my current project setup. I have developed a custom post type called "People" and have created several individual posts within it. At the moment, I have successfully implemented a modal using JavaScript with static content. Instead of disp ...

Recent Google algorithm changes impact websites built on AngularJS and JavaScript

Exciting news from Google today (May 28, 2014) - JavaScript content will now be rendered by the Googlebot itself! This means there's no need to worry about serving pre-rendered pages just for crawling purposes. You can find out more details on this an ...

The function 'downloadFunc' is not recognized as a valid function within the context of ReactJS custom hooks

Here is a unique custom hook that triggers when the user presses a button, calling an endpoint to download files as a .zip: import { useQuery } from 'react-query'; import { basePath } from '../../config/basePath'; async function downlo ...

Sorting functionality malfunctioning after dynamically adding new content using AJAX

Greetings to all, I have a question about my views. 1- Index 2- Edit In the index view, I have a button and AJAX functionality. When I click the button, it passes an ID to the controller which returns a view that I then append to a div. The Edit view con ...

Enlarging the modal overlay

My Angular/Bootstrap app features a small text area within a modal window that often contains lengthy content exceeding the size of the textarea and modal itself. I am looking to incorporate a button within the modal window that, when clicked, opens a lar ...

Tips for identifying the amount of <ul> elements contained within every div

Dealing with a large file structured in the same way, I am looking for a method to isolate a specific div, determine the number of ul's within it, and then iterate through each one to extract the value of every li element. <div class="experiment ...

The Webix component is experiencing a lack of refreshment

function refresh_group_items(){ //console.log("calling1"); window.setTimeout(function(){ $$("cfg").reconstruct() }, 3000); } $.ajax({ type: "POST", xhrFields:{ withCredentials: true }, beforeSend: function(reque ...

Transmit a pair of data values to the ajax request

How can I send two parameters to my JavaScript and retrieve them in a PHP file? Here is my HTML: <form method="post" action="testButtonSup.php"> <p> Please choose the service:<br /> <input type="radio" n ...

Element was removed upon clicking only once

Can anyone help me figure out why the behavior of .remove() with $postNav.remove(); is different here? When you click on "I'm a tag" for the first time, both the <li> and <ol> are deleted as expected. However, on the second click, only the ...

Why aren't the kittens loading in Next Js?

Following the guidance in the Next Js documentation, I created a next.config.js file to inform Next Js that I want to incorporate kittens into my app. The resource for the kittens can be found at: This is how the next.config.js file appears: module.expor ...

What is the best method for creating a loop script within a widget using script?

I am trying to implement a loop within a widget, however, the widget contains an internal script: <!DOCTYPE html> <html><head></head><body> <script> list=["AMAR3","BBDC4", "BEEF3", "BPAN4", "BRFS3", "B3SA3", "CVCB3" ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

"The Material UI date picker is encountering an issue with the error prop, which is being evaluated

I have developed a date picker that utilizes the Jalali calendar. While attempting to pass error checking using the error prop in the following code: <LocalizationProvider dateAdapter={AdapterJalali}> <MobileDatePicker label={lab ...

Omit certain table columns when exporting to Excel using JavaScript

I am looking to export my HTML table data into Excel sheets. After conducting a thorough research, I was able to find a solution that works for me. However, I'm facing an issue with the presence of image fields in my table data which I want to exclude ...

The variable "tankperson" is not recognized

While attempting to run an AJAX request upon page load, I encountered a particular error even though I have ensured that all the necessary libraries are included. The variable tankperson is derived from $_GET['name'] An unhandled ReferenceErr ...