2-4 Objects as data structure

This lab covers the basics of JavaScript objects and how to model complicated data using arrays and objects. The resultant data structure forms the basis of the JSON data format.

Objects

In JavaScript, an object is a collection of properties. Each property is a pair of name and value. (Sometimes JavaScript objects are used as key-value stores.) You can access each property with the dot notation.

// define an object with 3 properties
let peter = {
  firstName: "Peter",
  lastName: "Chan",
  age: 19
};
console.log(peter.lastName);  // "Chan"
peter.age ++;
console.log(`${peter.firstName} is now ${peter.age} years old.`);

Use assignment to change the value of an existing property, or add a new property.

let point = { };  // empty objects
point.x = 10; // add property
point.y = 8;
dir(point); // show structure, only avail in Chrome console

JavaScript objects are also a reference data type. (We mentioned in last section that arrays are reference data type.) When you assign an object variable to another variable, both variables will refer to the same object.

let p1 = { x: 10, y: 8, };  // adding a comma after the last property is ok
let p2 = p1;
p2.x = 3;
console.log(p1);  // p1 and p2 refer to { x: 3, y: 8 }

Functions can accept objects, and return objects. In the following, objects with the two properties x and y represent points on a plane.

function distance (p1, p2) {
  // the function Math.hypot() can also be used here
  const sum_sqr = (p1.x-p2.x)**2 + (p1.y-p2.y)**2;
  return Math.sqrt(sum_sqr);
}

function midpoint (p1, p2) {
  // create an object with properties x and y, and then return the object
  return {
    x: (p1.x+p2.x) / 2,
    y: (p1.y+p2.y) / 2
  };
}

let p1 = { x: 0, y: 0 }, p2 = { x: 3, y: 4 };
console.log(`Distance = ${distance(p1,p2)}`);

let mid = midpoint(p1, p2);
console.log(mid);

Complicated data

We can put an object as a property of an object.

let author = { firstName: 'Philip', lastName: 'Lei' };
let book = {
  title: 'Principles of gaming technology',
  author: author,  // a shorthand for this line is 'author,'
  publisher: 'McGraw Hill' 
};
console.log(`The textbook of comp414 is ${book.title}, of which one of the authors is ${book.author.firstName}.`);

We can also put objects as elements in an array, or put an array as a property of an object. This representation can model complicated data.

let lecturesOfComp312 = [
  { dow: 1, start: 1430, end: 1600, room: 'A210' },
  { dow: 5, start: 1130, end: 1300, room: 'A114' }
];

let comp312 = {
  code: 'comp312', 
  title: 'Internet programming II', 
  year: 3,
  lectures: lecturesOfComp312
};

const dowName = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];
console.log(`The lectures of '${comp312.title}' are on ${dowName[comp312.lectures[0].dow]} and ${dowName[comp312.lectures[1].dow]}`);

Destructuring and spread syntax

A recent feature called destructuring assignment makes it convenient to extract values from objects.

let book = {
  title: 'Principles of gaming technology',
  authors: [ 'Philip', 'Andrew' ],
  publisher: 'McGraw Hill',
  isbn13: '978-981-4923-23-1'
};

let { title, publisher, ...others } = book;
console.log(`Book title is ${title}.`);
// others keeps properties other than 'title' and 'publisher'

// you can also extract nested data
let { title, authors: [a1, a2] } = book;

The spread syntax ...object also allows to copy content of one object into another.

let p1 = { x: 2, y: 3 };
let p2 = { ...p1, z: 0 };  // convert the point on plain to a point in 3D space

A note on object notation

In addition to the dot notation, you can also use array notation to access a property in objects. Recent update to JavaScript also allows some non-ASCII characters in property names. (But property names cannot start with a digit.)

let cn2en = {
  : 'spring', : 'summer',
  : 'autumn',  : 'winter'
};
cn2en['春']  // 'spring'
cn2en.     // also works

The JavaScript language also has a for .. in control structure to enumerate the properties of an object. We skip its discussion because it is tricky to use.

Exercise

By mixing arrays and objects, you can use represent some complicated data. This forms the basis of the JSON data format.

In the following example, the object timetab represents the lecture timetable for 2016/17, semester 1. The property courses has array value, and contains an object for each course.

const timetab = {
  acadYear: "2016/17",
  semester: 1,
  courses: [
    {
      code: 'comp211', title: 'Database design', year: 2,
      lectures: [
        { dow: 2, start: 1130, end: 1300, room: 'A203' },
        { dow: 4, start: 1000, end: 1130, room: 'A318' }
      ]
    },
    {
      code: 'comp212', title: 'Programming II', year: 2,
      lectures: [
        { dow: 4, start: 1430, end: 1600, room: 'A317' },
        { dow: 3, start: 1600, end: 1730, room: 'A210' }
      ]
    },
    {
      code: 'comp214', title: 'Computer networks', year: 2,
      lectures: [
        { dow: 5, start: 1000, end: 1300, room: 'A206' }
      ]
    }
  ]
};

Use the time table data structure above to complete this exercise. Refer to the sample answers for sample output: ex2-4q1.js, ex2-4q2.js and ex2-4q3.js.

  1. Write a program to show the number of lectures of each course. The output should include course code, course title, and number of lectures per week.

  2. Write a program to print the content of the time table.

  3. Write a program to list the lectures on Thursday dow===4. The output should include course code, start and end time, and room.