Home
Map
Object, Dictionary ExamplesUse objects as dictionaries to provide lookups from keys to values.
Node.js
This page was last reviewed on Dec 13, 2023.
Object. 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.
Shows a dictionaryShows an object
Object details. 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 example. Imagine some animals—each has an associated number. We can place these animals in an object and get this number.
Part 1 We use a special literal syntax to declare the dictionary object. Keys and values can be added (or removed) later too.
Part 2 We access the "cat" field on the object twice. This key exists, so we get a value each time.
Part 3 Here we access a key that does not exist and the value returned is "undefined."
Shows a dictionary
// 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.
Warning This method returns an array. It also is defined by the specification to loop over the entire object. So it may be slow.
Shows an object
// 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
Quotes. 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.
Tip JavaScript files must be parsed before they are executed. Fewer characters can make them faster to parse.
// 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
Function. 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.
Here The box object has a width and height. We specify a 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
Key count. 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.
Result This object has three keys added to it. With 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
In operator. 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.
Tip This syntax can be used for feature detection—we can find supported properties on the "window" object, for example.
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
Nested object. 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.
Here We create an object that has a sub-object. We then link that object to the original object, creating a circular reference.
Warning This example helps us see how objects may be linked together, but it is not helpful in many real programs.
// 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
Multi-map. 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.
Start We create an empty object with the identifier "test." We then invoke the add() function to add things to the object.
Next Add() sees if an array exists at the requested key. If no array exists, a new, 1-element array is created.
Then If an array exists already, we push another value to it. So we add an element to an existing array.
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
Some notes. In many object-oriented languages, objects are heavier. Objects are instances of classes with constructors. In JavaScript though objects are lighter.
And Features like constructors and methods are optional. A class in its simplest form is a dictionary (or hash, or map).
Return object. We can return an object literal when we need to return multiple values from a function. The syntax for returning multiple values is clear.
Multiple Return Values
Review. We can access object properties directly or with a string lookup by name. Objects are versatile and can be though of as dictionaries.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 13, 2023 (simplify).
Home
Changes
© 2007-2024 Sam Allen.