A Node.js object is a dictionary that maps keys to values. With the name of a key, we access a value. We can specify integers and strings.
There are 2 ways to access a value from a key in an object. We can use a string
, or access the property directly on the object.
Dictionary
exampleImagine some animals—each has an associated number. We can place these animals in an object and get this number.
Keys
and values can be added (or removed) later too.// Part 1: create dictionary. var lookup = {"cat": 400, "dog": 600}; // Part 2: get the value for the cat string. console.log("LOOKUP SYNTAX 1: " + lookup.cat); console.log("LOOKUP SYNTAX 2: " + lookup["cat"]); // Part 3: get a nonexistent value. console.log("NONEXISTENT: " + lookup["?"]);LOOKUP SYNTAX 1: 400 LOOKUP SYNTAX 2: 400 NONEXISTENT: undefined
Object.keys
An object can have many keys, but we cannot access them in an easy way like we can an array. We must use a method like Object.keys
to get an array of the keys.
// Create object with 3 keys. var test = {"js": 1, "python": 0, "perl": -1}; // ... Add one more key. test["ruby"] = 0; // Get keys. var result = Object.keys(test); // ... Write the keys in a loop. for (var i = 0; i < result.length; i++) { console.log("KEY: " + result[i]); }KEY: js KEY: python KEY: perl KEY: ruby
Object literal syntax does not require quotes for keys. We can use string
or number keys with no quotes. This reduces the size of JavaScript files.
// Quotes are not needed in object literal keys. var colors = {yellow: "#FFFF00", silver: "#C0C0C0"}; console.log("VALUE: " + colors.yellow); console.log("VALUE: " + colors["silver"]);VALUE: #FFFF00 VALUE: #C0C0C0
With objects we can place a function in the value part for a key. So when the associated key is used, it can be called like a function.
function()
for the "area" key and call it directly.// Create a box object. // ... Set its width, height, and use a function for area. var box = { width: 2, height: 3, area: function() { return this.width * this.height; } }; // Write object properties. console.log("WIDTH: " + box.width); console.log("HEIGHT: " + box.height); console.log("AREA: " + box.area());WIDTH: 2 HEIGHT: 3 AREA: 6
An object has no length property. But it has a certain number of keys. With Object.keys
we can get those keys, and then use length on that variable.
Object.keys
we discover this information.// Example object with 3 keys. var test = {}; test["cat"] = 100; test[200] = "bird"; test["blue"] = ["red", "frog"]; // Use Object.keys to get keys from object. var keys = Object.keys(test); // ... Use length on keys to get key count. console.log("OBJECT KEY COUNT: " + keys.length);OBJECT KEY COUNT: 3
Sometimes we wish to see if a key exists in an object. We can use the "in" keyword to search the keys and return true if a key exists.
var data = {bird: 10, frog: 20}; // Use "in" to see if an object contains a key. if ("bird" in data) { console.log("TRUE"); } if ("apple" in data) { console.log("FALSE"); // Not reached. }TRUE
An object can be part of another object. And that nested object can also have sub-objects. We can construct entire trees of objects in this way.
// Create an object. var empty1 = {}; empty1.color = "orange"; // Create an object as part of the previous object. empty1.subobject = {}; empty1.subobject.color = "blue"; // Reference original object. empty1.subobject.subobject2 = empty1; // An object references itself. console.log("SUBOBJECT COLOR: " + empty1.subobject.subobject2.color);SUBOBJECT COLOR: orange
Sometimes we want to look up an array from a key. This type of collection is sometimes called a multi-map. One key has multiple values.
add()
function to add things to the object.Add()
sees if an array exists at the requested key. If no array exists, a new, 1-element array is created.function add(test, key, value) { if (!test[key]) { // Create 1-element array with this value. test[key] = [value]; } else { // Append element to existing array. test[key].push(value); } } // Create new object. var test = {}; // Add elements to arrays in object. add(test, "cat", 10); add(test, "cat", 20); add(test, "bird", 0); // Get arrays from object. var catItems = test["cat"]; console.log("CAT: " + catItems); var birdItems = test["bird"]; console.log("BIRD: " + birdItems);CAT: 10,20 BIRD: 0
In many object-oriented languages, objects are heavier. Objects are instances of classes with constructors. In JavaScript though objects are lighter.
class
in its simplest form is a dictionary (or hash, or map).We can return an object literal when we need to return multiple values from a function. The syntax for returning multiple values is clear.
We can access object properties directly or with a string
lookup by name. Objects are versatile and can be though of as dictionaries.