[javascript] 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.

This question is related to javascript dictionary key-value

The answer is


var dict = {};

dict['key'] = "testing";

console.log(dict);

works just like python :)

console output:

Object {key: "testing"} 

I happened to walk across this question looking for something similar. It gave me enough info to run a test to get the answer I wanted. So if anyone else wants to know how to dynamically add to or lookup a {key: 'value'} pair in a JavaScript object, this test should tell you all you might need to know.

var dictionary = {initialkey: 'initialValue'};
var key = 'something';
var key2 =  'somethingElse';
var value = 'value1';
var value2 = 'value2';
var keyInitial = 'initialkey';

console.log(dictionary[keyInitial]);

dictionary[key] =value;
dictionary[key2] = value2;
console.log(dictionary);

output

initialValue
{ initialkey: 'initialValue',
  something: 'value1',
  somethingElse: 'value2' }

An improvement on var dict = {} is to use var dict = Object.create(null).

This will create an empty object that does not have Object.prototype as it's prototype.

var dict1 = {};
if (dict1["toString"]){
    console.log("Hey, I didn't put that there!")
}
var dict2 = Object.create(null);
if (dict2["toString"]){
    console.log("This line won't run :)")
}

You could create a class Dictionary so you can interact with the Dictionary list easily:

_x000D_
_x000D_
class Dictionary {_x000D_
  constructor() {_x000D_
    this.items = {};_x000D_
  }_x000D_
  has(key) {_x000D_
    return key in this.items;_x000D_
  }_x000D_
  set(key,value) {_x000D_
    this.items[key] = value;_x000D_
  }_x000D_
  delete(key) {_x000D_
    if( this.has(key) ){_x000D_
      delete this.items[key]_x000D_
      return true;_x000D_
    }_x000D_
    return false;_x000D_
  }_x000D_
}_x000D_
_x000D_
var d = new Dictionary();_x000D_
d.set(1, "value1")_x000D_
d.set(2, "value2")_x000D_
d.set(3, "value3")_x000D_
console.log(d.has(2));_x000D_
d.delete(2);_x000D_
console.log(d.has(2));
_x000D_
_x000D_
_x000D_


Its as simple as:

var blah = {}; // make a new dictionary (empty)

or

var blah = {key: value, key2: value2}; // make a new dictionary with two pairs 

then

blah.key3 = value3; // add a new key/value pair
blah.key2; // returns value2
blah['key2']; // also returns value2

In ES6 you can do this:

let cake = '';

let pan = {
  [cake]: '',
};

// Output -> { '': '' }

Old Way

let cake = '';
let pan = {};
pan[cake] = '';

// Output -> { '': '' }

First Initialise Array Globally

var dict = []

Add Object into Dictionary

dict.push(
     { key: "One",value: false},
     { key: "Two",value: false},
     { key: "Three",value: false});

Output : 
   [0: {key: "One", value: false}
    1: {key: "Two", value: false}
    2: {key: "Three", value: false}]

Update Object from Dictionary

Object.keys(dict).map((index) => {        
  if (index == 1){
    dict[index].value = true
  }
});

Output : 
   [0: {key: "One", value: false},
    1: {key: "Two", value: true},
    2: {key: "Three", value: false}]

Delete Object from Dictionary

Object.keys(dict).map((index) => {              
      if (index == 2){
        dict.splice(index)
      }
    });

Output : 
    [0: {key: "One", value: false},
     1: {key: "Two", value: true}]

how about the one liner for creating a key value pair?

let result = { ["foo"]: "some value" };

and some iterator function like reduce to dynamically convert an array to a dictionary

_x000D_
_x000D_
var options = [_x000D_
  { key: "foo", value: 1 },_x000D_
  { key: "bar", value: {id: 2, name: "two"} },_x000D_
  { key: "baz", value: {["active"]: true} },_x000D_
];_x000D_
_x000D_
var result = options.reduce((accumulator, current) => {_x000D_
  accumulator[current.key] = current.value;_x000D_
  return accumulator;_x000D_
}, {});_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_


In case if someone needs to create a dictionary object dynamically you can use the following code snippet

_x000D_
_x000D_
   let vars = [{key:"key", value:"value"},{key:"key2", value:"value2"}];
     let dict={}
     vars.map(varItem=>{
              dict[varItem.key]=varItem.value
            })

    console.log(dict)
_x000D_
_x000D_
_x000D_


var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1

In modern javascript (ES6/ES2015), one should use Map data structure for dictionary. The Map data structure in ES6 lets you use arbitrary values as keys.

const map = new Map();
map.set("true", 1);
map.set("false", 0);

In you are still using ES5, the correct way to create dictionary is to create object without a prototype in the following way.

var map = Object.create(null);
map["true"]= 1;
map["false"]= 0;

There are many advantages of creating a dictionary without a prototype object. Below blogs are worth reading on this topic.

dict-pattern

objects-as-maps


You can use maps with Map, like this:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');

I ran into this problem.. but within a for loop. The top solution did not work (when using variables (and not strings) for the parameters of the push function), and the others did not account for key values based on variables. I was surprised this approach (which is common in php) worked..

  // example dict/json                  
  var iterateDict = {'record_identifier': {'content':'Some content','title':'Title of my Record'},
    'record_identifier_2': {'content':'Some  different content','title':'Title of my another Record'} };

  var array = [];

  // key to reduce the 'record' to
  var reduceKey = 'title';

  for(key in iterateDict)
   // ultra-safe variable checking...
   if(iterateDict[key] !== undefined && iterateDict[key][reduceKey] !== undefined)
    // build element to new array key
     array[key]=iterateDict[key][reduceKey];

JavaScript's Object is in itself like a dictionary. No need to reinvent the wheel.

var dict = {};

// Adding key-value -pairs
dict['key'] = 'value'; // Through indexer
dict.anotherKey = 'anotherValue'; // Through assignment

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:key value:value
  // key:anotherKey value:anotherValue
}

// Non existent key
console.log(dict.notExist); // undefined

// Contains key?
if (dict.hasOwnProperty('key')) {
  // Remove item
  delete dict.key;
}

// Looping through
for (var item in dict) {
  console.log('key:' + item + ' value:' + dict[item]);
  // Output
  // key:anotherKey value:anotherValue
}

Fiddle


Since you've stated that you want a dictionary object (and not an array like I assume some understood) I think this is what you are after:

var input = [{key:"key1", value:"value1"},{key:"key2", value:"value2"}];

var result = {};

for(var i = 0; i < input.length; i++)
{
    result[input[i].key] = input[i].value;
}

console.log(result); // Just for testing

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to dictionary

JS map return object python JSON object must be str, bytes or bytearray, not 'dict Python update a key in dict if it doesn't exist How to update the value of a key in a dictionary in Python? How to map an array of objects in React C# Dictionary get item by index Are dictionaries ordered in Python 3.6+? Split / Explode a column of dictionaries into separate columns with pandas Writing a dictionary to a text file? enumerate() for dictionary in python

Examples related to key-value

Iterate through dictionary values? How can I get key's value from dictionary in Swift? How to add a new object (key-value pair) to an array in javascript? How to search if dictionary value contains certain string with Python Python: How to check if keys exists and retrieve value from Dictionary in descending priority How do you create a dictionary in Java? how to prevent adding duplicate keys to a javascript array How to update value of a key in dictionary in c#? How to create dictionary and add key–value pairs dynamically? How to count frequency of characters in a string?