How do you convert an array of items or key-value pairs into an object in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you convert an array of items or key-value pairs into an object in JavaScript?

message-square
0

To convert an array of [key, value] pairs into a plain object in JavaScript, use Object.fromEntries(entries) (the inverse of Object.entries()). To convert a flat array of items—or an array of objects keyed by a property such as id—into an object, map entries into [key, value] pairs and pass them to Object.fromEntries() (or accumulate non-mutating updates with .reduce()).


1. Converting Key-Value Pairs with Object.fromEntries()

Object.fromEntries() takes any iterable of [key, value] pairs and builds a new plain object:

// Convert an array of [key, value] pairs into a plain object
const pairEntries = [
  ["theme", "dark"],
  ["pageSize", 25],
  ["notifications", true]
];

const configObject = Object.fromEntries(pairEntries);
console.log("From entries:", configObject);

// Works with URLSearchParams or Map too
const params = new URLSearchParams("sort=asc&page=2");
console.log("From query params:", Object.fromEntries(params));
  • Clean and idiomatic: Object.fromEntries() is built into ES2019+ and handles arrays, Map instances, and URLSearchParams.
  • Last duplicate key wins: If an array contains multiple entries with the same key, later entries overwrite earlier ones.

2. Converting Arrays of Items or Objects into a Lookup Object

When starting from an array of items or records rather than [key, value] tuples, transform each element with .map() into [key, value] pairs before calling Object.fromEntries(), or use .reduce() when you need custom collision/grouping logic:

// Index an array of objects by a unique key (e.g., id) without mutating the source array
function indexByKey(items, keyField) {
  if (!Array.isArray(items)) {
    return {};
  }

  const entries = items
    .filter((item) => item && typeof item === "object" && keyField in item)
    .map((item) => [String(item[keyField]), item]);

  return Object.fromEntries(entries);
}

const users = [
  { id: 101, name: "Bilal", role: "admin" },
  { id: 102, name: "Zoya", role: "editor" }
];

const usersById = indexByKey(users, "id");
console.log("Indexed users:", usersById);
  • O(1) key lookups: Turning a list of records into a dictionary/map object avoids repeated .find() scans.
  • Preserves original array: Neither .map() nor Object.fromEntries() mutates the source users array.

3. Common Traps to Avoid

Converting arrays into objects in JavaScript can introduce prototype collisions, key overwrites, or unintended mutation:

  • Using untrusted user input as object keys without care: Plain objects inherit properties from Object.prototype (such as toString, constructor, or __proto__)—when keys come from dynamic/untrusted data and you need safe arbitrary key lookups without prototype collisions, consider a Map or Object.create(null).
  • Silent overwrites when keys duplicate: Both Object.fromEntries() and acc[key] = val overwrite earlier values when duplicate keys exist—use .reduce() to group values into arrays instead if you want multiple items per key.
  • Accidental object reference sharing: Indexing objects from an array stores references to those same object instances in the resulting dictionary, so mutating a record later affects both structures.

TL;DR: Use Object.fromEntries(pairs) for [key, value] entries (or Object.fromEntries(items.map(...)) for item arrays), and use .reduce() when you need custom grouping or conflict rules.

Are you converting [key, value] tuples, indexing an array of objects by id, or grouping items with duplicate keys into arrays?