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
var dictionary = {};//create new object
dictionary["key1"] = value1;//set key1
var key1 = dictionary["key1"];//get key1
In ES6 you can do this:
let cake = '
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' }
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
var options = [
{ key: "foo", value: 1 },
{ key: "bar", value: {id: 2, name: "two"} },
{ key: "baz", value: {["active"]: true} },
];
var result = options.reduce((accumulator, current) => {
accumulator[current.key] = current.value;
return accumulator;
}, {});
console.log(result);
You could create a class Dictionary so you can interact with the Dictionary list easily:
class Dictionary {
constructor() {
this.items = {};
}
has(key) {
return key in this.items;
}
set(key,value) {
this.items[key] = value;
}
delete(key) {
if( this.has(key) ){
delete this.items[key]
return true;
}
return false;
}
}
var d = new Dictionary();
d.set(1, "value1")
d.set(2, "value2")
d.set(3, "value3")
console.log(d.has(2));
d.delete(2);
console.log(d.has(2));
You can use maps with Map, like this:
var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');