0

I get some data from the server with variables that are not valid in Javascript.

Example : Short_%

Is there a way to turn it into a valid one ?

Also, related question : how do I call such a variable name ? THis : myObject.Short_% won't work.

John Doe
  • 1,092
  • 3
  • 12
  • 25
  • What exactly do you want to accomplish? There isn't a way to "redefine" what a valid variable name is in javascript. – Nathan Chu Dec 09 '20 at 00:24
  • you can refer to myObject['Short_%'] though. it doesn't make it a valid variable name but a property name is just a string. – bmacnaughton Dec 09 '20 at 00:26
  • you can iterate by object's keys and rename keys whichever way you want – Nonik Dec 09 '20 at 00:28
  • @nthnchu : I was thinking there may be a way to use unicode or something to make the variable name valid. I'm defining types for my data which I get from the server – John Doe Dec 09 '20 at 00:30

1 Answers1

1

It is possible to use Short_% as name, the difference is how to access this value. Use the square bracket syntax to set/get a value:

var myvalue=myObject['Short_%'];

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation. This notation is also very useful when property names are to be dynamically determined (when the property name is not determined until runtime)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties

F.Igor
  • 4,119
  • 1
  • 18
  • 26