Computer Programming 1 (JavaScript) • Problem Solving & Mini-Projects

Building JSON Address Book — I can build a simple JSON-based address book (array of objects) with lookup and update at my level.

Learn to store, search, and update contact data using arrays of objects in JavaScript.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Before computers existed, people kept contact information in physical address books — small notebooks where you could flip to a letter tab and find someone's phone number. As software replaced paper, developers needed a way to represent that same structured data inside a program. The challenge was finding a format that was easy for both humans to read and machines to parse. That search led to JSON (JavaScript Object Notation), a lightweight data format that mirrors how JavaScript already organizes information.

1995 • JavaScript Is Born

Brendan Eich creates JavaScript at Netscape in just 10 days. The language includes built-in support for objects and arrays, laying the groundwork for structured data.

2001 • JSON Emerges

Douglas Crockford introduces JSON as a simple text format for exchanging data between a server and a browser. Its syntax is based directly on JavaScript object and array literals.

2006 • JSON Becomes a Standard

RFC 4627 formally specifies JSON. Web APIs from companies like Google, Twitter, and Facebook adopt it, making JSON the dominant data-exchange format on the internet.

2013–Present • JSON Everywhere

JSON is used in databases (MongoDB), configuration files (package.json), and nearly every modern web and mobile app. Understanding JSON is now a core developer skill.

Today, almost every app you use — from your phone's Contacts to Snapchat — stores and exchanges data in JSON or a similar format. The question this lesson addresses is straightforward: How do you build, search, and update a collection of structured records using JavaScript arrays and objects? By building a simple address book, you will learn patterns that apply to any data-driven project.

SECTION 2

Core Principles & Definitions

Before you write any code, you need to understand the building blocks. An address book is really just a list of contacts, and each contact has several fields — name, phone, email, and so on. JavaScript gives you two key structures to model this: objects (which hold labeled fields) and arrays (which hold ordered lists). When you combine them — an array of objects — you get a simple but powerful data model.

1

Object

A collection of key-value pairs wrapped in curly braces { }. Each key is a string label (like "name"), and each value can be a string, number, boolean, or even another object.
2

Array

An ordered list wrapped in square brackets [ ]. Each item has a numeric index starting at 0. Arrays let you group many items of the same type together.
3

Array of Objects

An array where every element is an object with the same structure. This is the standard pattern for representing a collection of records — like rows in a spreadsheet.
4

Lookup (Search)

Finding a specific object inside an array by checking a field value. JavaScript provides methods like .find() and .filter() to make this easy.
5

Update (Mutate)

Changing a value inside an existing object. Because objects are stored by reference, you can modify a property and the change is reflected everywhere that object is used.
✦

KEY TAKEAWAY

Think of an array of objects like a filing cabinet. The cabinet is the array — it holds many folders in order. Each folder is an object — it contains labeled fields for one person's info. Looking up a contact is like flipping through folders until you find the right name. Updating is like pulling out that folder, erasing the old phone number, and writing a new one.

SECTION 3

Visual Explanation — The Address Book Structure

addressBook (Array)[]Index 0name:"Alice Lee"phone:"555-0101"email:"alice@e.co"city:"Austin"Index 1name:"Bob Chen"phone:"555-0202"email:"bob@e.co"city:"Denver"Index 2name:"Cara Diaz"phone:"555-0303"email:"cara@e.co"city:"Miami"Lookup ExampleaddressBook.find(c => c.name === "Bob Chen")→ returns Index 1 objectUpdate Examplecontact.phone = "555-9999"→ Bob's phone is now 555-9999
The diagram shows the addressBook array containing three contact objects at indices 0, 1, and 2. Each object has the same four keys: name, phone, email, and city. The amber box demonstrates a lookup using .find(), and the green box shows a property update.

Notice that every contact object follows the same shape — the same set of keys with different values. This consistency is what makes the array of objects pattern so useful. You can loop through the array, compare a field, and confidently access any property you need because you know every object has it. The lookup finds the matching object by its name, and the update modifies a single property on that same object reference.

SECTION 4

How It Works — CRUD Operations

Most data-driven programs revolve around four operations known by the acronym CRUD: Create, Read, Update, and Delete. Your address book uses the same operations. Let's map each one to the JavaScript code you will write.

Create — Adding a Contact

To add a new contact, you build an object literal and push it onto the array. The .push() method appends the item to the end. Here is the pattern:

CREATE PATTERN

addressBook.push(name:"...",phone:"...",email:"...",city:"...")addressBook.push({ name: "...", phone: "...", email: "...", city: "..." })

addressBook is the array. .push() adds the new object at the next available index.

Read — Looking Up a Contact

The .find() method accepts a callback function and returns the first object where the callback returns true. If no match exists, it returns undefined.

LOOKUP PATTERN

constresult=addressBook.find(contact=>contact.name==="BobChen")const result = addressBook.find(contact => contact.name === "Bob Chen")

The arrow function contact => contact.name === "Bob Chen" checks each object's name field. result will hold the matching object or undefined.

Update — Changing a Field

Once you have a reference to the object (from .find()), you can change any property using dot notation or bracket notation. The original object inside the array is modified because objects are stored by reference.

UPDATE PATTERN

result.phone="555−9999"result.phone = "555-9999"

Assigns a new value to the phone property. You can also use bracket notation: result["phone"] = "555-9999".

Delete — Removing a Contact

You can remove a contact by finding its index with .findIndex() and then using .splice() to cut it out. Alternatively, .filter() returns a new array that excludes the unwanted entry.

DELETE PATTERN

addressBook=addressBook.filter(c=>c.name!=="BobChen")addressBook = addressBook.filter(c => c.name !== "Bob Chen")

Creates a new array keeping every contact whose name is not "Bob Chen". The old array is replaced.

SECTION 5

Detailed Breakdown — Data Flow Diagram

Understanding the flow of data through your program is just as important as knowing the syntax. When a user wants to find or change a contact, the program follows a clear sequence: receive input, search the array, act on the result, and provide output. The diagram below visualizes this flow for both lookup and update operations.

Address Book Operations — Data FlowUser Input (name to find)Loop through addressBook arrayaddressBook.find(c => c.name === input)Match found?NOYES"Contact not found"Return contact objectDisplay info OR update fieldcontact.phone = newValueOutput updated contact
This flowchart traces a typical operation: the user provides a name, the program searches the array, and the outcome branches based on whether a match is found. If a match exists, the program can either display the contact or update one of its fields.
⚠

Always Check for undefined

When .find() returns undefined, trying to access a property on it (like result.phone) will crash your program with a TypeError. Always wrap updates in an if (result) check first.

SECTION 6

Worked Example — Building the Address Book

Let's build a complete mini-project from scratch. We will create an address book, add contacts, look one up by name, update their phone number, and then list everyone in a specific city.

Address Book — Full Walkthrough

  1. 1

    Step 1 — Initialize the Array

    Start with an empty array, then push three contact objects. Each object has four keys: name, phone, email, and city.
    let addressBook = [ { name: "Alice Lee", phone: "555-0101", email: "alice@mail.com", city: "Austin" }, { name: "Bob Chen", phone: "555-0202", email: "bob@mail.com", city: "Denver" }, { name: "Cara Diaz", phone: "555-0303", email: "cara@mail.com", city: "Austin" } ];
  2. 2

    Step 2 — Lookup by Name

    Use .find() to search for Bob Chen. The callback compares each contact's name to the target string. Because "Bob Chen" exists at index 1, bob will hold a reference to that object.
    const bob = addressBook.find(c => c.name === "Bob Chen"); console.log(bob); // { name: "Bob Chen", phone: "555-0202", email: "bob@mail.com", city: "Denver" }
  3. 3

    Step 3 — Guard Against undefined

    Before updating, check that the lookup actually found something. If you searched for a name that doesn't exist, .find() returns undefined, and accessing a property on undefined would throw an error.
    if (bob) { console.log("Found:", bob.name); } else { console.log("Contact not found."); }
  4. 4

    Step 4 — Update the Phone Number

    Inside the if block, assign a new value to bob.phone. Because bob is a reference to the object inside addressBook, the array is updated too — no copy was made.
    bob.phone = "555-9999"; console.log(addressBook[1].phone); // "555-9999" ← updated in the original array
  5. 5

    Step 5 — Filter by City

    Use .filter() to get all contacts in Austin. Unlike .find(), which returns one object, .filter() returns a new array containing every match.
    const austinContacts = addressBook.filter(c => c.city === "Austin"); console.log(austinContacts.length); // 2 // [{ name: "Alice Lee", ... }, { name: "Cara Diaz", ... }]

SECTION 7

Array Methods — Strengths & Limitations

JavaScript offers several array methods that are useful for address book operations. Each method has trade-offs, so choosing the right one depends on what you need to accomplish. The table below compares the key methods you will use most often.

MethodReturnsBest For
.find()First matching object (or undefined)Looking up a single contact by a unique field like name
.filter()New array of all matches (empty array if none)Getting all contacts in a city, or matching a partial search
.findIndex()Index number (or −1)When you need the position for .splice() to delete
.push()New length of the arrayAdding a new contact to the end of the array
.splice()Array of removed itemsRemoving a contact at a specific index (mutates the array)
.forEach()undefinedLooping through every contact to display or log

Comparison of key array methods for address book operations

✦

KEY TAKEAWAY

Use .find() when you expect exactly one result (like a username lookup). Use .filter() when there could be multiple results (like all contacts in the same city). Think of .find() like using Ctrl+F to jump to the first match, and .filter() like highlighting every match on the page.

SECTION 8

Connection to Advanced Concepts

The JSON address book you are building is a simplified version of the data layer found in real applications. As you advance, the same concepts scale up dramatically. The table below shows how each element of your project maps to professional tools and techniques.

This LessonAdvanced Version
Array of objects stored in a variableDatabase table (SQL) or document collection (MongoDB)
.find() for lookupSQL SELECT ... WHERE query
Dot notation to update a fieldSQL UPDATE ... SET statement
.filter() for multiple matchesREST API endpoints with query parameters
Data stored in memory (lost on refresh)Persistent storage with localStorage, files, or cloud databases

How today's concepts map to professional development

One natural next step is learning JSON.stringify() and JSON.parse(), which convert your array to a text string and back. This lets you save the address book to localStorage so it persists between browser sessions. Eventually, you will connect your front-end code to a back-end server and a real database — but the mental model of CRUD on an array of objects stays exactly the same.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain the difference between .find() and .filter() when searching an address book array. When would you choose one over the other?
Show answer
The .find() method returns the first single object that matches the callback condition, or undefined if nothing matches. The .filter() method returns a new array containing every object that matches, which could be empty, one item, or many items. You would use .find() when looking up a contact by a unique identifier like a full name, and .filter() when you expect multiple results, such as all contacts living in the same city.

Question 2: BASIC CALCULATION

Given the array below, write a single line of code that finds the contact whose name is "Dana Kim". let contacts = [ { name: "Dana Kim", phone: "555-1111" }, { name: "Eli Fox", phone: "555-2222" } ];
Show answer
The correct code is: const dana = contacts.find(c => c.name === "Dana Kim");. This iterates through the contacts array and returns the first object where c.name strictly equals "Dana Kim". The variable dana will hold { name: "Dana Kim", phone: "555-1111" }.

Question 3: INTERMEDIATE

Write a function called updateEmail(addressBook, name, newEmail) that finds a contact by name and updates their email. If the contact is not found, the function should return the string "Contact not found". If the update is successful, return the updated contact object.
Show answer
Here is one correct solution: function updateEmail(addressBook, name, newEmail) { const contact = addressBook.find(c => c.name === name); if (!contact) { return "Contact not found"; } contact.email = newEmail; return contact; } The function first uses .find() to locate the matching contact. The if (!contact) guard checks for undefined (which is falsy). If a match exists, the email property is reassigned, and the updated object is returned. Because objects are passed by reference, the original array is also updated.

Question 4: APPLIED

You are building a classroom roster app. Each student object has name, grade (a number 9–12), and email. Write code that: (1) creates an array with at least 3 students in different grades, (2) filters to get only 10th graders, and (3) logs each 10th grader's name and email to the console.
Show answer
A complete solution: let roster = [ { name: "Ava", grade: 10, email: "ava@school.edu" }, { name: "Ben", grade: 11, email: "ben@school.edu" }, { name: "Chloe", grade: 10, email: "chloe@school.edu" }, { name: "Dev", grade: 9, email: "dev@school.edu" } ]; const sophomores = roster.filter(s => s.grade === 10); sophomores.forEach(s => console.log(s.name, s.email)); The .filter() call returns a new array containing only the objects where grade equals 10 (Ava and Chloe). Then .forEach() iterates through the filtered array and logs each student's name and email. This pattern — filter then iterate — is extremely common in real applications.

Question 5: CRITICAL THINKING

Imagine two contacts in your address book share the same name (e.g., two people named "Jordan Lee"). Explain why using .find() to look up by name could be a problem, and propose at least two different strategies to handle this situation.
Show answer
The .find() method stops at the first match, so if two contacts are named "Jordan Lee", you will always get the first one and never reach the second. This is a problem because your lookup silently ignores duplicate names. Strategy 1: Add a unique id field (like a number or UUID) to each contact and search by id instead of name. This guarantees uniqueness. Strategy 2: Use .filter() instead of .find() so you receive an array of all matches, and then let the user pick the correct one based on additional details like email or city. Both strategies address the root problem: names are not inherently unique identifiers.

SUMMARY

Lesson Summary

Summary

In this lesson you learned how to model structured data using an array of objects — the foundational pattern behind nearly every data-driven application. Each contact in the address book is a JavaScript object with key-value pairs for name, phone, email, and city. The collection of contacts lives inside an array, giving you ordered, indexed access to every record.

You practiced the four CRUD operations: Create with .push(), Read with .find() and .filter(), Update with dot notation on the found object, and Delete with .filter() or .splice(). Always guard against undefined when a lookup finds no match. These skills transfer directly to databases, APIs, and every professional tool you will encounter as you advance in programming.

Varsity Tutors • Computer Programming 1 (JavaScript) • Building JSON Address Book