0
var obj = {
a?: "abc"
}

Want to access Key Which is Not in a valid format.

Giving me Error.

I'm accessing it like this obj.a.

and this is throwing an error.

const obj = { a?: 'aaa' }
console.log(obj.a)
Harish Soni
  • 1,796
  • 12
  • 27
Rajat Dhoot
  • 185
  • 3
  • 17

3 Answers3

1

This could work (not tested)

obj['a?'];
Oulalahakabu
  • 504
  • 3
  • 6
1

Valid property names

Looking at the ECMAScript spec grammar, we can see that a property name can be either an identifier name (i.e. identifiers + reserved words), a string literal, or a numeric literal.

Identifier names are a superset of identifiers; any valid identifier and any reserved word is a valid identifier name.

[...]

When can the quotes be omitted?

Unless an object key is a numeric literal or a valid identifier name, you need to quote it to avoid a syntax error from being thrown. In other words, quotes can only be omitted if the property name is a numeric literal or a valid identifier name. Of course, if the property name is a string literal, it’s already quoted by definition

source: https://mathiasbynens.be/notes/javascript-properties

To solve your specific issue you can use quotes:

var obj = {
'a?': "abc"
}

obj['aj']

Full answer can be found at https://stackoverflow.com/a/9571440/1211174

Community
  • 1
  • 1
oak
  • 2,898
  • 2
  • 32
  • 65
  • 1
    First, *You can do* is not an explanation. Please explain why your answer solves anything. Second, since you know the issue, you are more likely to find a better duplicate. You should look for it rather than answering. – Rajesh Dec 05 '17 at 09:28
  • @Rajesh you are right, fixed – oak Dec 05 '17 at 09:34
-2

The key should be a simple string in JavaScript, so if you change from a? to a, it should work.