Course contentsShow
← JavaScript
Lesson 623 of 2,72315. ObjectsFree lesson

Dynamic Object Building Patterns

Build objects iteratively using computed keys to aggregate data from arrays or maps.

Dynamic Object Building Patterns

What you'll learn: How to build objects piece-by-piece using computed keys to aggregate data from arrays or other collections.

The Core Idea

Instead of hardcoding object properties upfront, you can construct objects iteratively by looping through data and using computed property names. This is incredibly useful when you need to transform arrays or maps into structured objects where the keys themselves come from your data.

Think of it like building a custom shelf: instead of buying one with fixed compartments, you're adding labeled sections one at a time based on what you actually need to store.

Building Objects from Data

When you combine loops with computed keys, you can aggregate information dynamically:

const votes = [
  { candidate: 'Alice', count: 5 },
  { candidate: 'Bob', count: 3 },
  { candidate: 'Alice', count: 2 }
];

const results = {};

for (const vote of votes) {
  if (results[vote.candidate]) {
    results[vote.candidate] += vote.count;
  } else {
    results[vote.candidate] = vote.count;
  }
}

console.log(results); // { Alice: 7, Bob: 3 }

Here, the object keys ('Alice', 'Bob') come directly from the data, not from code we wrote beforehand.

Pattern: Grouping by Property

const products = [
  { name: 'Apple', category: 'Fruit' },
  { name: 'Carrot', category: 'Vegetable' },
  { name: 'Banana', category: 'Fruit' }
];

const grouped = {};

for (const product of products) {
  const key = product.category;
  
  if (!grouped[key]) {
    grouped[key] = [];
  }
  
  grouped[key].push(product.name);
}

console.log(grouped);
// { Fruit: ['Apple', 'Banana'], Vegetable: ['Carrot'] }

Key Takeaway: Dynamic object building lets you transform lists into structured objects by computing keys on-the-fly, making your code adapt to whatever data it receives rather than hardcoding structure ahead of time.