Programming
Array Conversion
Object-Oriented Programming
JavaScript
Coding Tips

How to convert an array into an object?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Converting an array into an object is common in JavaScript when you need key-based lookup instead of index-based access. The best method depends on your input shape: plain value arrays, key-value pairs, or arrays of records. Good conversions are explicit about key generation and collision behavior.

Case 1: Value Array to Index-Keyed Object

If you just want object keys as indices, spread and Object.assign both work.

javascript
1const fruits = ["apple", "banana", "cherry"];
2
3const bySpread = { ...fruits };
4const byAssign = Object.assign({}, fruits);
5
6console.log(bySpread); // "0":"apple", "1":"banana", "2":"cherry"
7console.log(byAssign);

This preserves all values but keys are strings of numeric indices.

Case 2: Build Object With Custom Keys Using reduce

Most real use cases need semantic keys.

javascript
1const users = [
2  { id: "u1", name: "Ana" },
3  { id: "u2", name: "Ben" },
4  { id: "u3", name: "Chen" },
5];
6
7const usersById = users.reduce((acc, user) => {
8  acc[user.id] = user;
9  return acc;
10}, {});
11
12console.log(usersById.u2.name); // Ben

reduce is flexible and clear for key derivation.

Case 3: Array of Pairs With Object.fromEntries

If your array already contains key-value tuples, Object.fromEntries is the cleanest approach.

javascript
1const pairs = [
2  ["theme", "dark"],
3  ["language", "en"],
4  ["timezone", "UTC"],
5];
6
7const config = Object.fromEntries(pairs);
8console.log(config.theme); // dark

This is concise and avoids manual loops.

Handling Duplicate Keys Intentionally

When multiple items map to the same key, later values overwrite earlier ones by default.

javascript
1const arr = [
2  { id: "u1", score: 10 },
3  { id: "u1", score: 15 },
4];
5
6const latestWins = arr.reduce((acc, row) => {
7  acc[row.id] = row.score;
8  return acc;
9}, {});
10
11console.log(latestWins); // "u1":15

If you need grouped values, accumulate arrays instead.

javascript
1const grouped = arr.reduce((acc, row) => {
2  if (!acc[row.id]) acc[row.id] = [];
3  acc[row.id].push(row.score);
4  return acc;
5}, {});

Define this behavior up front to avoid silent data loss.

Choosing Object Versus Map

Object is great for JSON-compatible structures and simple lookups. Map is better when:

  • key types are not strings.
  • insertion order behavior matters strongly.
  • you need frequent add and remove operations with large key sets.

Example with Map:

javascript
const map = new Map(users.map((u) => [u.id, u]));
console.log(map.get("u3").name); // Chen

Use object when output must serialize naturally to JSON.

Performance and Memory Notes

Conversion is linear in array length for all common approaches. Performance differences are usually minor compared with correctness and readability. For very large arrays, avoid creating unnecessary intermediate arrays before conversion.

For example, prefer one-pass reduce if you otherwise would map then transform repeatedly.

TypeScript Tip for Safer Conversions

In TypeScript, annotate accumulator type for better safety.

typescript
1type User = { id: string; name: string };
2
3const usersById = users.reduce<Record<string, User>>((acc, user) => {
4  acc[user.id] = user;
5  return acc;
6}, {});

This improves autocomplete and catches key or value shape mistakes.

For API boundary code, validate keys before conversion so malformed records do not silently produce undefined object entries that are difficult to debug later.

Common Pitfalls

A common pitfall is converting arrays to objects without defining key strategy, then discovering unstable or meaningless keys later. Another issue is ignoring duplicate keys and accidentally overwriting values. Teams also use object conversion where Map would better match runtime behavior, especially for non-string keys. Using spread on very large arrays can be convenient but less explicit than purpose-driven reducers. Finally, converting data for lookup without documenting shape can create mismatch between frontend and backend assumptions.

Summary

  • Pick conversion strategy based on array shape and lookup requirements.
  • Use spread or Object.assign for index-keyed conversion.
  • Use reduce or Object.fromEntries for semantic keys.
  • Define duplicate-key policy explicitly to avoid silent overwrites.
  • Consider Map when key types or mutation patterns exceed object strengths.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.