LANGUAGE » JAVASCRIPT

Dictionary

Basic

INFO

Everything in javascript is an Object, but to differentiate these from hash tables, I'll call it dictionary here.

Instantiate:

javascript
const animal = 'seagull';
const mydict = {
   cat: 'Meow',
   'dog': 'Bark',
   [animal]: 'Mew',
};

Access values (either one is OK):

javascript
const cat = mydict.cat;
const dog = mydict['dog'];

Delete a key/value pair:

javascript
delete mydict.cat;

Get number of key/value pairs, can also be used to check if dictionary is empty:

javascript
const dictLength = Object.keys(mydict).length;

Methods

MethodDescription
Object.prototype.hasOwnProperty.call(obj, key)
Object.hasOwn(object, key)
Return true if object owns property, false otherwise.
Object.assign(target, source)Copy all own properties from source to target.
Object.keys(obj)Return an array of keys.
Object.values(obj)Return an array of values.
Object.entries(obj)Return an array of key-value pairs.

Loop key/value pairs

javascript
for (let key in mydict) {
  console.log(`${key}: ${mydict[key]}`);
}

Object.entries(mydict).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

Object.keys(mydict).forEach(function (key) {});

Create a copy

javascript
// Shallow
Object.assign({}, mydict);

// Deep
JSON.parse(JSON.stringify(mydict));

let $ = require('jquery');
$.extend(true, {}, oldDict);

let _ = require('lodash');
_.clonedeep(original);