0

I'm trying to create objects from a key/value list. My Problem is, that Object Properties have to be valid JavaScript identifiers. At least with Adobe ExtendScript I can perfectly create an Object with a wrong Property (See Example: wrong-key -> "-"-Literal is invalid).

var kvp = ["key;value", "wrong-key;value"];
var obj = {};

for (var i = 0 ; i < kvp.length; i++) {
    pair = kvp[i].split(";");
    obj[pair[0]] = pair[1]; 
}
alert (obj.key);
alert (obj.wrong-key); // -> Throws an Error

Of course I could run a replace(/-/,"_"), but is there any encoding/escaping function out there to accomplish this goal more generally?

thanks, gregor

1 Answer 1

1

you can access those properties with special chars using the array notation

console.log(obj["wrong-key"]);
Sign up to request clarification or add additional context in comments.

8 Comments

Ok. But just for the record, is "wrong-key" a valid js identifier?
What do you mean by "valid" js identifier?? Sure, you can perfectly have a property name like you have "wrong-key", although I'd avoid that if possible due to the issues you encountered.
@Juri valid in terms of the Specification. You're workaraound will do, but as you can imagina if no control about the input-data.
@grefel: If you have no control over the input data, then you cannot know the key. In that case you cannot even write in your code but you have to retrieve it dynamically. And then, the only way to access the property is bracket notation. Or am I misunderstanding you?
This is not a workaround, this is an alternative way of accessing JavaScript object's properties. What kind of use case do you have? Where does this key-value list come from??
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.