insert into the dictionary

Asked

Viewed 356 times

2

I have a dictionary in javascript:

var dict = {}

And I need to insert a value inside it. I tried to use

dict.add("chave":"valor");

but it didn’t work.

How can I add a new key/value inside the dictionary?

3 answers

3

In fact the variable dict is not a dictionary is a javascript object.

Javascript has no dictionary, if you want to use a structure that holds key and value you can use one javascript object or Map.

With objects you can create the attributes dynamically as already commented in the answers of Leandrade and Hudsonph.

With Map you have advantages with methods map.get(key) that searches the value based on the key, map.has(key) checks if there is a certain key in the structure and map.delete(key) removes based on key.

var dict = new Map();
    
// Adiciona a chave e o valor no mapa
dict.set('chave', 'valor');
console.log('Chave e valor adicionados');

// Com item inserido
console.log('has', dict.has('chave'));
console.log('get',dict.get('chave'));

console.log('Chave inexistente');
// Com um item não inserido
console.log('has', dict.has('chave inexistente'));
console.log('get', dict.get('chave inexistente'));

// Remove a chave e o valor no mapa
dict.delete('chave');
console.log('Chave e valor removida')

// Com item removido
console.log('has', dict.has('chave'));
console.log('get', dict.get('chave'));

2


a small change

var dict = {};
dict.chave ="valor";
console.log(dict);

2

A way to do:

var dict = {};
dict['chave'] = "valor";
console.log(dict);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.