How do you dynamically build a dictionary or key-value map in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you dynamically build a dictionary or key-value map in JavaScript?

message-square
0

To dynamically build a dictionary or key-value map in JavaScript, use new Map() whenever keys are dynamic strings/numbers from untrusted or runtime data, non-string keys (objects, symbols, numbers without string coercion), or when you need frequent insertions/deletions and an exact .size count; use a plain object ({}) or Object.create(null) when building JSON-serializable records or static/known key structures. Using Map or Object.create(null) avoids prototype-property collisions like "toString", "constructor", or "__proto__" that can trip up plain {} dictionaries.


1. Building a Dynamic Dictionary with Map (Recommended for Dynamic Keys)

Create a Map and populate entries with .set(key, value) (or initialize from an iterable of [key, value] pairs), giving O(1) average lookups, safe dynamic keys, and built-in .size:

// Dynamically group items into a Map by key
function groupByKey(items, getKey) {
  if (!Array.isArray(items) || typeof getKey !== "function") {
    throw new TypeError("Expected items array and getKey selector function.");
  }

  const map = new Map();

  for (const item of items) {
    const key = getKey(item);
    const bucket = map.get(key);

    if (bucket) {
      bucket.push(item);
    } else {
      map.set(key, [item]);
    }
  }

  return map;
}

// Example usage:
const records = [
  { role: "admin", name: "Nadia" },
  { role: "user", name: "Tariq" },
  { role: "admin", name: "Zoya" }
];

const byRole = groupByKey(records, (r) => r.role);
console.log(byRole.size);             // 2
console.log(byRole.get("admin"));     // [{ role: "admin", name: "Nadia" }, { role: "admin", name: "Zoya" }]
console.log(byRole.has("moderator")); // false
  • No prototype key clashes: Keys like "constructor", "valueOf", or "__proto__" are stored as ordinary map entries without touching Object.prototype.
  • Preserves insertion order & supports any key type: Objects, arrays, numbers, and strings all work as distinct keys.

2. Building Plain Objects Dynamically (Object.create(null) vs. {})

When you need a plain object—such as for JSON serialization (JSON.stringify) or interop with APIs expecting plain objects—prefer Object.create(null) for untrusted or arbitrary dynamic string keys so inherited prototype properties are not present:

// Build a prototype-free dictionary object for arbitrary string keys
function countOccurrences(keys) {
  if (!Array.isArray(keys)) {
    throw new TypeError("Expected keys to be an array.");
  }

  const counts = Object.create(null);

  for (const rawKey of keys) {
    const key = String(rawKey);
    counts[key] = (counts[key] ?? 0) + 1;
  }

  return counts;
}

// Example usage:
const tally = countOccurrences(["GET", "POST", "GET", "toString"]);
console.log(tally["GET"]);      // 2
console.log(tally["toString"]); // 1 (not a function; exact count)
  • Null-prototype safety: Object.create(null) has no inherited hasOwnProperty or toString keys, avoiding collisions with user-supplied keys.
  • Avoid mutating __proto__ on {}: Assigning obj["__proto__"] = ... on a normal object alters its prototype rather than setting a regular own property.

3. Converting Between Map, Entries, and Plain Objects

Convert cleanly between Map, [key, value] entry arrays, and plain objects using Object.fromEntries(), Object.entries(), and new Map(...):

// Convert between Map, [key, value] entries, and a plain object
const scoreMap = new Map([
  ["math", 92],
  ["physics", 88]
]);

scoreMap.set("chemistry", 95);

const scoreObject = Object.fromEntries(scoreMap);
// { math: 92, physics: 88, chemistry: 95 }

const roundTrippedMap = new Map(Object.entries(scoreObject));
console.log(roundTrippedMap.get("chemistry")); // 95
console.log(JSON.stringify(scoreObject));      // '{"math":92,"physics":88,"chemistry":95}'
  • JSON requires plain objects or arrays: JSON.stringify(new Map(...)) serializes to "{}", so convert with Object.fromEntries(map) first when sending over JSON.
  • Use Object.hasOwn(obj, key) on plain objects: When checking own properties on a standard object ({}), prefer Object.hasOwn(obj, key) over key in obj so prototype properties do not return true.