0

I refer below post but did not get it properly See here

I was tried 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 and remove the key and value pairs and I don’t know how to achieve that.

Is anyone know how to create that object and add key value pairs dynamically and perform crud operation on it?

I’ve tried:

var dict = [{key:"key", value:"value"}];
dict[0].key = "keys";
dict[0].value = "vals";
console.log(dict);
// return null value of dict object.

So that doesn’t work. Thank you

Hardik Virani
  • 1,687
  • 7
  • 23
  • 36

2 Answers2

0

You can use Map.
Map object has functions to set keys and values dynamically using .set(key, value)

var dict = new Map();
dict.set("key1", "value1");
dict.set("key2", "value2");
dict.set("key3", "value3");

for (var [key, value] of dict) {
  console.log(key + ' = ' + value);
}

Razana N.
  • 70
  • 5
0

I've tried dynamically using .set(key, value) and it's work

var dict = new Map();
dict.set("key1", "value1");

for (var [key, value] of dict) {
  console.log(key + ' = ' + value);
}