Computer Programming 1 (JavaScript) • Data I/O & JSON

Tabular Data as Array of Objects — I can represent tabular data as an array of objects and explain the structure.

Learn how spreadsheets and databases translate into JavaScript arrays of objects for powerful data manipulation.

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

SECTION 1

Historical Context & Motivation

Long before computers existed, people organized information in rows and columns. Think of a class roster taped to a classroom door or a handwritten ledger tracking business expenses. This idea of tabular data — information arranged in a table with rows and columns — is one of the oldest and most intuitive ways humans store structured information. The challenge that emerged with computers was how to represent these familiar tables in a format that software can read, transmit, and manipulate.

Early computing relied on punch cards and fixed-width text files to store table-like records. As the internet grew, developers needed a lightweight format to send structured data between a web browser and a server. That need gave rise to JSON (JavaScript Object Notation), which maps beautifully onto JavaScript's own syntax for objects and arrays. Today, the pattern of representing each row of a table as a JavaScript object — and the entire table as an array of objects — is used by virtually every web application, from social media feeds to online stores.

1970 • Relational Databases

Edgar Codd published his groundbreaking paper on relational databases, formalizing the concept of data stored in tables with rows and columns.

1995 • JavaScript Is Born

Brendan Eich created JavaScript for Netscape Navigator, introducing objects and arrays as core data types in the language.

2001 • JSON Emerges

Douglas Crockford popularized JSON as a lightweight alternative to XML, using JavaScript's native object/array syntax for data interchange.

2010s • APIs Everywhere

REST APIs became the standard way web apps communicate, almost universally returning arrays of objects as JSON to represent lists of records.

The central question this lesson addresses is straightforward: How do you take a table of data and faithfully represent it in JavaScript code? Understanding this pattern unlocks your ability to work with real-world data sources — from weather APIs to student grade books.

SECTION 2

Core Principles & Definitions

Before diving into code, you need to understand four foundational ideas that connect spreadsheets and databases to JavaScript data structures. Each concept builds on the last, so take them in order.

1

Tabular Data

Data organized into rows and columns, like a spreadsheet. Each column represents a category of information (e.g., name, age). Each row represents one record or entry.
2

JavaScript Object

A collection of key-value pairs wrapped in curly braces { }. Each key is a property name (like a column header), and each value holds that property's data for one record.
3

JavaScript Array

An ordered list of values wrapped in square brackets [ ]. Elements are accessed by their numeric index, starting at 0. Arrays keep items in a predictable sequence.
4

Array of Objects

An array where every element is an object. This pattern represents a table: the array is the collection of rows, and each object is one row whose keys match the column headers.
✦

KEY TAKEAWAY

Think of a spreadsheet as a filing cabinet. The whole cabinet is the array. Each folder inside is an object (one row). The labels on each folder's tabs — Name, Grade, Score — are the keys, and the information written on each tab is the value. An array of objects is simply a filing cabinet full of identically-labeled folders.

SECTION 3

Visual Explanation — From Table to Code

The diagram below shows how a simple three-row table maps directly to a JavaScript array of objects. Study the color coding: each row of the table becomes one object in the array, and each column header becomes a key inside every object.

Spreadsheet TableArray of Objects (JS)namegradescore"Alice"1092"Bob"1185"Carlos"1078const students = [{name: "Alice",grade: 10,score: 92},{name: "Bob",grade: 11,score: 85},{name: "Carlos",grade: 10,score: 78}];↑ Each colored rowbecomes one object →Row 1 → Object at index 0Row 2 → Object at index 1Row 3 → Object at index 2
Each colored row in the spreadsheet table (left) maps to a correspondingly colored object in the JavaScript array (right). The column headers — name, grade, score — become the keys in every object.

Notice three important details in the diagram. First, the column headers from the table do not appear as separate data — they become the property keys repeated inside every object. Second, each row is self-describing: if you pull out one object, it carries all of its labels with it, unlike a CSV row where you need to remember what column 3 means. Third, the outer square brackets [ ] wrap all the objects, creating a single array you can loop through with for loops or array methods.

SECTION 4

How the Structure Works — Syntax Deep Dive

Let's break down the exact JavaScript syntax piece by piece. Understanding each layer — the array wrapper, the object literals, and the key-value pairs — will let you read and write these structures confidently.

Layer 1 — The Outer Array

The entire dataset lives inside an array declared with square brackets. This array can hold zero or more elements. In the tabular-data pattern, every element is an object. You typically assign the array to a const variable so you can reference it later.

ARRAY DECLARATION

constdataTable=[obj0,obj1,obj2,…,objn−1];const dataTable = [ obj₀, obj₁, obj₂, … , objₙ₋₁ ];

The array holds n objects, indexed from 0 to n − 1. Access any row with dataTable[i].

Layer 2 — Each Object (One Row)

Each object uses curly braces and contains key-value pairs separated by commas. The key is a string (the column name) and the value can be any JavaScript type — a string, number, boolean, or even another array or object.

OBJECT LITERAL

key1:value1,key2:value2,key3:value3{ key₁: value₁, key₂: value₂, key₃: value₃ }

Keys are written without quotes if they are valid identifiers (e.g., name). Values are written with quotes for strings ("Alice") and without for numbers (92).

Layer 3 — Accessing Data

You chain bracket and dot notation to drill into a specific value. For example, students[0].name first grabs the object at index 0 (Alice's record) and then reads the name property, returning "Alice". You can also use bracket notation for both: students[0]["name"] gives the same result.

DATA ACCESS PATTERN

arrayName[rowIndex].propertyKey→valuearrayName[rowIndex].propertyKey → value

students[2].score → 78 (third row, score column)

⚠

Common Mistake

Remember that array indices start at 0, not 1. If your table has 5 rows, the valid indices are 0 through 4. Using students[5] on a 5-element array returns undefined.

SECTION 5

Data Types in Objects & the JSON Connection

Each value in an object can be one of several JavaScript types. Choosing the right type matters because it determines what operations you can perform on that data. The table below summarizes the most common types you'll encounter in tabular data and shows how they look in code.

Data TypeExample ValueUse Case
String"Alice"Names, labels, descriptions — any text data
Number92Scores, prices, quantities — values you'll do math on
BooleantrueYes/no flags, such as "enrolled" or "passed"
nullnullAn intentionally empty value — the data is missing or unknown
Array["math", "art"]A list within a cell, like multiple hobbies or tags

Common JavaScript data types found inside objects representing table rows

Anatomy of One Object in the Array// students[1]{name:"Bob",← key: string valuegrade:11,← key: number valuescore:85,← key: number valueenrolled:true,← key: boolean valuehobbies:["chess", "coding"]← key: array value}Key (property name)String valueNumber valueBooleanNested ArrayEach key-value pair corresponds to one column of data for this row.
The anatomy of a single object from the students array, showing how keys (cyan) pair with values of different types (yellow for strings, green for numbers, red for booleans, orange for nested arrays).

This structure aligns perfectly with JSON (JavaScript Object Notation). When you receive data from a web API, it almost always arrives as a JSON string that, once parsed, becomes exactly this kind of array of objects. The function JSON.parse() converts a JSON string into a live JavaScript array, and JSON.stringify() converts it back. Mastering the array-of-objects pattern means you are already fluent in reading and writing JSON.

SECTION 6

Worked Example — Building and Querying a Table

Imagine you're building a small app to track your school's inventory of library books. The librarian gives you a spreadsheet with four columns: title, author, year, and available. Let's convert this into an array of objects and then answer questions about the data.

Library Book Inventory

  1. 1

    Step 1 — Identify Columns as Keys

    The spreadsheet has four column headers: title, author, year, and available. These become the keys that repeat in every object.
    Keys: title, author, year, available
  2. 2

    Step 2 — Translate Each Row into an Object

    Row 1 of the spreadsheet says: "To Kill a Mockingbird", "Harper Lee", 1960, Yes. In JavaScript, this row becomes: { title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960, available: true }. Notice that "Yes" is translated into the boolean true since it represents a yes/no flag.
  3. 3

    Step 3 — Repeat for All Rows and Wrap in an Array

    Repeat the conversion for each row and place all objects inside square brackets, separated by commas:
    const books = [ { title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960, available: true }, { title: "1984", author: "George Orwell", year: 1949, available: false }, { title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925, available: true } ];
  4. 4

    Step 4 — Access a Specific Value

    To find the author of the second book, use index 1 (remember, counting starts at 0): books[1].author.
    Result: "George Orwell"
  5. 5

    Step 5 — Loop to Find Available Books

    Use a for loop to print only available books: for (let i = 0; i < books.length; i++) { if (books[i].available) { console.log(books[i].title); } }. The .length property tells you how many objects (rows) are in the array.
    Output: "To Kill a Mockingbird" and "The Great Gatsby"

SECTION 7

Array of Objects vs. Other Structures

An array of objects isn't the only way to represent tabular data in JavaScript. You might wonder why we don't use a two-dimensional array (an array of arrays) or a single flat object. The table below compares these approaches so you can appreciate the trade-offs.

ApproachStrengthsLimitations
Array of ObjectsSelf-describing: each row carries its own column names as keys. Easy to read and extend with new columns. Works directly with JSON APIs.Slightly more memory usage because keys are repeated in every object. More typing when creating the data manually.
2D Array (Array of Arrays)Compact: no repeated keys. Fast to create for small datasets.Not self-describing: you must remember that index 0 is name, index 1 is grade, etc. Harder to maintain as the table grows.
Object of Arrays (Column-Oriented)Efficient for column-level operations like computing the average of all scores.Difficult to work with individual rows. Data for one record is spread across multiple arrays.

Comparison of three common approaches for representing tabular data in JavaScript

🏆

WHY ARRAY OF OBJECTS WINS

Imagine moving to a new school. If your records are an array of objects, it's like handing over a complete folder with your name, grades, and contact info all labeled inside. A 2D array is like handing over a row of numbers with a separate sticky note explaining what each number means — easy to lose, easy to mix up. In professional programming, clarity and self-documentation almost always beat minor memory savings.

SECTION 8

Connection to JSON, APIs, and Databases

The array-of-objects pattern you've learned is not just a classroom exercise — it is the exact format used by virtually every modern web API. When a weather app fetches a five-day forecast, it receives an array of five objects, each containing keys like date, high, low, and description. Understanding this pattern prepares you for working with real APIs and databases in more advanced courses.

This CourseAdvanced Topic
Hardcode an array of objects in your JS fileFetch data from a REST API using fetch() and parse the JSON response
Access values with dot/bracket notationUse array methods like .filter(), .map(), and .reduce() for complex queries
Console-log resultsDynamically render data into HTML tables or lists using the DOM
Three to five rows of sample dataQuery databases with thousands of rows (SQL, MongoDB) that return the same array-of-objects format

How today's skills connect to advanced programming topics

The core skill — reading and writing an array of objects — stays the same whether you're building a to-do app or querying a million-row database. Learn it well now, and you'll find that advanced topics like API consumption, data visualization, and server-side programming feel like natural extensions of what you already know.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

In the array-of-objects pattern for tabular data, what does each object represent, and what do the keys inside each object represent? Explain in your own words.
Show answer
Each object represents one row (one record) of the table. The keys inside each object represent the column headers — the categories of information being tracked. For example, in a table of students, each object is one student, and keys like name, grade, and score correspond to the columns. The values paired with those keys hold the actual data for that particular row.

Question 2: BASIC CALCULATION

Given the following array, what does pets[2].species evaluate to? const pets = [ { name: "Buddy", species: "dog", age: 4 }, { name: "Whiskers", species: "cat", age: 7 }, { name: "Goldie", species: "fish", age: 1 } ];
Show answer
The expression evaluates to "fish". Here's why: pets[2] accesses the third element (index 2) of the array, which is the object { name: "Goldie", species: "fish", age: 1 }. Then .species reads the value of the species key in that object, which is "fish".

Question 3: INTERMEDIATE

A teacher has the following spreadsheet: | student | period | average | |---------|--------|---------| | Maya | 2 | 91 | | Ethan | 3 | 84 | | Zoe | 2 | 97 | Write the JavaScript code to represent this table as an array of objects. Then write a for loop that prints the names of students with an average above 90.
Show answer
First, create the array: const roster = [ { student: "Maya", period: 2, average: 91 }, { student: "Ethan", period: 3, average: 84 }, { student: "Zoe", period: 2, average: 97 } ]; Then loop through it: for (let i = 0; i < roster.length; i++) { if (roster[i].average > 90) { console.log(roster[i].student); } } This prints "Maya" and "Zoe" because their averages (91 and 97) are both greater than 90. Ethan's average of 84 does not pass the condition.

Question 4: APPLIED

You're building a snack shop menu app. The menu has items with a name, price, category ("drink" or "food"), and whether the item is vegetarian. Write the array of objects for at least three menu items using appropriate data types for each property. Then explain which data type you chose for each key and why.
Show answer
const menu = [ { name: "Veggie Wrap", price: 5.99, category: "food", vegetarian: true }, { name: "Lemonade", price: 2.50, category: "drink", vegetarian: true }, { name: "Chicken Tenders", price: 6.49, category: "food", vegetarian: false } ]; The name and category keys use strings because they hold text labels. The price key uses a number because you need to do arithmetic with it (e.g., calculating totals). The vegetarian key uses a boolean because it's a yes-or-no question — the item either is or isn't vegetarian. Choosing correct types ensures your code can perform the right operations on each piece of data.

Question 5: CRITICAL THINKING

A classmate argues that a 2D array like [["Alice", 10, 92], ["Bob", 11, 85]] is better than an array of objects because it uses less code. Write a short paragraph explaining at least two scenarios where the array-of-objects approach would prevent bugs or confusion that the 2D array approach might cause.
Show answer
First, consider a scenario where a developer needs to add a new column (for example, email) to the data. With a 2D array, every piece of code that accesses data by index must be updated: what used to be index 2 for score might shift, causing silent bugs. With an array of objects, the new key is simply added and existing code referencing .score still works fine. Second, if another developer reads the code months later, students[0][2] is meaningless without checking a comment or header row, while students[0].score is immediately clear. Self-describing data reduces misunderstandings and maintenance errors, which matters far more than saving a few characters of code.

SUMMARY

Lesson Summary

Summary

Tabular data — information organized in rows and columns — is one of the most common data formats you'll encounter. In JavaScript, the standard way to represent a table is as an array of objects. The outer array (square brackets) holds the collection of rows, and each object (curly braces) represents one row. The keys inside each object correspond to the column headers, and the values hold the actual cell data — strings, numbers, booleans, or even nested arrays.

You access specific data by chaining bracket notation (for the row index) with dot notation (for the property key), like data[0].name. This pattern is self-describing, easy to extend, and maps directly to JSON — the universal format used by web APIs. Mastering it now sets you up for working with real-world data in every future programming course.

Varsity Tutors • Computer Programming 1 (JavaScript) • Tabular Data as Array of Objects