Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create dictionary and add key–value pairs dynamically?

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.

Does anyone know how to 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.

like image 224
KenEucker Avatar asked Aug 25 '11 19:08

KenEucker


People also ask

How do you add a key-value pair in an object dynamically?

To add dynamic key-value pairs to a JavaScript array or hash table, we can use computed key names. const obj = {}; obj[name] = val; to add a property with the value of name string as the property name. We assign val to as the property's value.

How do you add key-value pairs to an existing dictionary?

In Python, we can add multiple key-value pairs to an existing dictionary. This is achieved by using the update() method. This method takes an argument of type dict or any iterable that has the length of two - like ((key1, value1),) , and updates the dictionary with new key-value pairs.

How do you create a dictionary using keys and values?

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.

How do you create an empty dictionary and add value?

To create an empty dictionary, first create a variable name which will be the name of the dictionary. Then, assign the variable to an empty set of curly braces, {} . Another way of creating an empty dictionary is to use the dict() function without passing any arguments.


1 Answers

var dict = []; // create an empty array  dict.push({     key:   "keyName",     value: "the value" }); // repeat this last part as needed to add more key/value pairs 

Basically, you're creating an object literal with 2 properties (called key and value) and inserting it (using push()) into the array.


Edit: So almost 5 years later, this answer is getting downvotes because it's not creating an "normal" JS 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 key and value properties. 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 JS 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 JS names. You can just do this:

// object literal with properties var dict = {   key1: "value1",   key2: "value2"   // etc. }; 

Or use regular dot-notation to set properties after creating an object:

// empty object literal with properties added afterward var dict = {}; dict.key1 = "value1"; dict.key2 = "value2"; // etc. 

You do want the bracket notation if you've got keys that have spaces in them, special characters, or things like that. E.g:

var dict = {};  // this obviously won't work dict.some invalid key (for multiple reasons) = "value1";  // but this will dict["some invalid key (for multiple reasons)"] = "value1"; 

You also want bracket notation if your keys are dynamic:

dict[firstName + " " + lastName] = "some value"; 

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 Date object gets converted to its string representation:

dict[new Date] = "today's value";  console.log(dict); // => { //      "Sat Nov 04 2016 16:15:31 GMT-0700 (PDT)": "today's value" //    } 

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:

var objA = { a: 23 },     objB = { b: 42 };  dict[objA] = "value for objA"; dict[objB] = "value for objB";  console.log(dict); // => { "[object Object]": "value for objB" } 

Despite objA and objB being completely different and unique elements, they both have the same basic string representation: "[object Object]".

The reason Date doesn't behave like this is that the Date prototype has a custom toString method which overrides the default string representation. And you can do the same:

// a simple constructor with a toString prototypal method function Foo() {   this.myRandomNumber = Math.random() * 1000 | 0; }  Foo.prototype.toString = function () {   return "Foo instance #" + this.myRandomNumber; };  dict[new Foo] = "some value";  console.log(dict); // => { //      "Foo instance #712": "some value" //    } 

(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, JS will use the object's own toString implementation, if any, or use the default string representation.

like image 125
Flambino Avatar answered Nov 08 '22 11:11

Flambino