From post:
Sending a JSON array to be received as a Dictionary<string,string>,
I’m trying to do this same thing as that post. The only issue is that I don’t know what the keys and the values are upfront. So I need to be able to dynamically add the key and value pairs and I don’t know how to do that.
How can I create that object and add key value pairs dynamically?
I’ve tried:
var vars = [{key:"key", value:"value"}];
vars[0].key = "newkey";
vars[0].value = "newvalue";
But that doesn’t work.
Use:
Basically, you’re creating an object literal with two properties (called
keyandvalue) and inserting it (usingpush()) into the array.This does not create a "normal" JavaScript object literal (aka map, aka hash, aka dictionary).
It is however creating the structure that OP asked for (and which is illustrated in the other question linked to), which is an array of object literals, each with
keyandvalueproperties. Don’t ask me why that structure was required, but it’s the one that was asked for.But, but, if what you want in a plain JavaScript object – and not the structure OP asked for – see tcll’s answer, though the bracket notation is a bit cumbersome if you just have simple keys that are valid JavaScript names. You can just do this:
Or use regular dot-notation to set properties after creating an object:
You do want the bracket notation if you’ve got keys that have spaces in them, special characters, or things like that. E.g:
You also want bracket notation if your keys are dynamic:
Note that keys (property names) are always strings, and non-string values will be coerced to a string when used as a key. E.g., a
Dateobject gets converted to its string representation:Note however that this doesn’t necessarily "just work", as many objects will have a string representation like
"[object Object]"which doesn’t make for a non-unique key. So be wary of something like:Despite
objAandobjBbeing completely different and unique elements, they both have the same basic string representation:"[object Object]".The reason
Datedoesn’t behave like this is that theDateprototype has a customtoStringmethod which overrides the default string representation. And you can do the same:(Note that since the above uses a random number, name collisions can still occur very easily. It’s just to illustrate an implementation of
toString.)So when trying to use objects as keys, JavaScript will use the object’s own
toStringimplementation, if any, or use the default string representation.