jack sparrow
jack sparrow

Reputation: 173

Able to create a map with strings as keys but when the key is referred it gives "Unexpected number error"

Please look into the code snippet below:

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

Now the map is created but when I try to refer it with the key like:

mapObj.123 it gives me a "Unexpected number" error? But if I try the same with mapObj[123] or mapObj["123"] it shows me the correct object. What do I need to do to refer the same using the '.' notation?

Upvotes: 0

Views: 26

Answers (3)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123533

What do I need to do to refer the same using the '.' notation?

In this case, you can't.

When using the dot notation, the property's name must be a valid identifier:

In JavaScript, identifiers can contain only alphanumeric characters (or "$" or "_"), and may not start with a digit.

So, to access a numeric key, like 123, you'll have to use bracket notation:

myObj[123]

If you're rather determined to use dot notation, adding an alpha prefix to the keys would permit its use:

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

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

console.log(myObj.id_123);

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36458

Javascript properties, when accessed via dot notation (a.x) can't begin with a digit.

If the object was

{ one1: foo }

then

mapObj.one1

would work. Since the id values are numeric, you need to use bracket notation (a[x]):

mapObj[1]

or

mapObj["1"]

Upvotes: 1

CasualProgrammer
CasualProgrammer

Reputation: 1

Change

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

To

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

Upvotes: -1

Related Questions