Explain Codes LogoExplain Codes Logo

Best way to store a key=>value array in JavaScript?

javascript
key-value-pairs
javascript-objects
es6-map
Alex KataevbyAlex Kataev·Sep 25, 2024
TLDR

Choose a JavaScript object for an uncomplicated and potent key-value store.

let store = { key: 'value' }; console.log(store.key); // prints 'value', easy-peasy!

Objects offer instant access to values through string keys, this makes managing data a cakewalk.

Why should you choose JavaScript objects?

JavaScript objects are your first port of call for maintaining keys and values in a loosely-typed manner. Here's the rationale:

  • Quick access: Objects allow seamless data access via object[key].
  • Clean slate (Objects +1): Object.create(null) gets rid of those default pesky prototype keys.
  • Enumerability: for...in lets you conveniently loop over an object's keys.

The need for ES6 Map

Objects are cool but ES6 Map came equipped with some extra arsenals to tackle objects' limitations:

  • Flexible keys: Maps can have any value as a key, not just strings.
  • Size attribute: No more counting properties, thanks to Maps size property.
  • Iteration options: Maps offer .keys(), .values(), .entries() for easy iteration.

Choosing the right structure for data storage

Your specific requirements should help decide:

  • Objects: For simple key-value pairs.
  • Maps: For storage with dynamic keys.
  • Array of objects: To list key-value pairs.

Combine arrays and objects

Merging these two can pave a way for complex data structures:

  • Arrays holding objects: Arrays use numeric indexes and objects inside hold named keys.
  • Objects holding arrays: Objects use named keys and arrays provide tabular storage.

What to use and when?

  • Numerical data: Arrays with numeric indexes are efficient.
  • Mixed key types: A Map would provide dynamic keys.
  • Tags as keys: If keys are tags or labels, then go with the objects.

jQuery can help too

In case you're already using jQuery, leverage the $.each to iterate harmoniously over arrays or object properties.

Practical advice

  • Destructuring Maps: To print key-values easily, use the destructuring assignment.

    let myMap = new Map([['key1', 'value1'], ['key2', 'value2']]); for (const [key, value] of myMap) { console.log(`${key}: ${value}`); // ...and voila! }
  • Store your structure: Define key-value pairs globally or within a class for greater scope and ease of reference.