Basics of Javascript Objects

We will start with simple object literals.

Basics of Javascript Objects

Most typically objects are parts of classes and instantiated by calling the class constructor. We will discuss these objects shortly. For now we will learn some basic methods for working with objects, by looking at “objects as dictionaries”.

Basic object/dictionary tasks

Here are some key tasks with dictionaries and how to carry them out:

Creating an object
let o = { key1: val1, key2: val2, ... };
Setting an object key
o[keyString] = newValue;
o.key = newValue;
Accessing a key value
o[keyString];
o.key;
Checking if a key exists
o.hasOwnProperty(keyString);
Traversing all keys-value pairs
// Approach 1
for (let key in o) {
    if (o.hasOwnProperty(key)) {      // <--- Must do this check!
      let value = o[key];             // Declaration should be earlier
      // Do things with key, value
    }
}
// Approach 2
let keys = Object.keys(o);     // <-- Returns array of keys
for (let i = 0; i < keys.length; i += 1) {
  let key = keys[i];          // Declaration should be earlier
  let value = o[key];         // Declaration should be earlier
  // Do things with key, value
}