How to check if a key is in a javascript dictionary

4

I have the following dictionary:

diccionario = {1: "uno", 2: "dos", 3: "tres"}

I would like to see if it contains a certain key, for example, 2. How can I know?

And by the way ... I would also like to know how to check if a value is in the dictionary. How is a value given and a key returned?

    
asked by Mr. Baldan 25.04.2018 в 17:33
source

5 answers

6

The dictionary concept here is ambiguous:

Objects as dictionaries (or Hash Maps)

What you call a dictionary is a basic object in Javascript.

To obtain the keys you have this functionality:

let diccionario = {1: "uno", 2: "dos", 3: "tres"};

let claves=Object.keys(diccionario);

console.log(claves);

On the other hand, you could go through the keys in the following way:

let diccionario = {1: "uno", 2: "dos", 3: "tres"};

for (let i in diccionario) {
  console.log('la clave es',i);
}

But to know if a key exists, in a pragmatic way, you can simply compare with undefined :

let diccionario = {1: "uno", 2: "dos", 3: "tres"};

for (let i=0;i<5;i++) {
  if (diccionario[i] === undefined) {
    console.log('la clave',i,'no está presente');
  } else {
    console.log('la clave',i,'está presente');
  }
}

While it is true that the key can be present, but not save any value, in practice there is no difference between considering that it is not present or that its value is undefined:

let objeto={ a: 1, b: undefined, c: 3};

console.log(Object.keys(objeto));

console.log('Miramos b:', objeto.b);
console.log('Miramos d:', objeto.d);

delete objeto.a;

console.log('Hemos quitado a, las claves restantes son',Object.keys(objeto));
console.log('comprobamos su valor:', objeto.a);

If you want to know if really the key does not exist, even with undefined value, there is the hasOwnProperty method:

let obj = {1: "uno", 2: undefined, 3: "tres"};

console.log("existe 1?", obj.hasOwnProperty(1));
console.log("existe 2?", obj.hasOwnProperty(2)); //aunque sea undefined

real dictionary (using a class designed for that purpose)

Say what you really want is a dictionary, Javascript has the class Map , which gives more possibilities than a simple object, such as keys can be objects and not merely text or numbers, or you can ask how many elements there are:

var miMapa = new Map();

//Potenciales claves
var claveObj = {},
    claveFunc = function () {},
    claveCadena = "una cadena";

// asignando valores
miMapa.set(claveCadena, "valor asociado con 'una cadena'");
miMapa.set(claveObj, "valor asociado con claveObj");
miMapa.set(claveFunc, "valor asociado with claveFunc");

console.log("Tamaño",miMapa.size);
console.log("buscando con una clave string",miMapa.get(claveCadena));    
console.log("buscando con una clave objeto",miMapa.get(claveObj));
console.log("buscando con una clave función",miMapa.get(claveFunc));

console.log('Existe "una cadena" como clave?',miMapa.has("una cadena"));
    
answered by 25.04.2018 / 17:42
source
2

I think the best way to verify the key is as follows:

diccionario.hasOwnProperty(llave); //Retorna valor booleano.

Every Object descended from Object inherits the hasOwnProperty method. This method can be used to determine if an object has the property specified as a direct property of that object; unlike the in operator, this method does not verify the prototype string of the object.

    
answered by 25.04.2018 в 17:50
1

To know that your dictionary has a specific key you can use this code:

Object.keys(diccionario).includes("2")

With Object.keys (dictionary) you get all the keys of the dictionary object and with the includes function you search if there is a value "2" in the list of keys.

Good to get the keys for a particular value would be worth this:

var valor = "tres";
diccionario = {1: "uno", 2: "dos", 3: "tres", "prueba": "tres"}
var clavesPorValor = [];
Object.keys(diccionario).forEach( propiedad => { 
         if (diccionario[propiedad] === valor) { 
               clavesPorValor.push(propiedad);
         }
})
console.log(clavesPorValor);

I hope it serves you.

Greetings.

    
answered by 25.04.2018 в 17:42
1

To find out if it contains a key, you could use .hasOwnProperty() :

var diccionario = {1: "uno", 2: "dos", 3: "tres"};
console.log(diccionario.hasOwnProperty("0"));
console.log(diccionario.hasOwnProperty("1"));

To find out if it contains a value, you could use the methods of Object :

  • Object.values() returns the enumerable values of the object, in the same order that would be seen in a for in
  • Object.keys() returns the enumerable keys of the object, in the same order that would be seen in a for in

var diccionario = {
  1: "uno",
  2: "dos",
  3: "tres"
};

llaveParaValor(diccionario, "uno");
llaveParaValor(diccionario, "cinco");


function llaveParaValor(o, val) {
  var i = Object.values(o).indexOf(val);
  if (i >= 0) {
    console.log(Object.keys(o)[i]);
  } else {
    console.log("no existe el valor");
  }
}
    
answered by 25.04.2018 в 17:49
1

To obtain the keys:

Object.keys(objeto)

To obtain the values:

Object.values(objeto)

To give value to a key:

objeto["clave"] = nuevo_valor;
    
answered by 25.04.2018 в 17:54