From post:
Sending a JSON array to be received as a Dictionary
I’m trying to do this same thing as that post. The only issue is that I d
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 :)")
}
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
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