Introduction
Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods, and may contain all other JavaScript data types, such as strings, numbers, and Booleans.
All objects in JavaScript descend from the parent Object
constructor. Object
has many useful built-in methods we can use and access to make working with individual objects straightforward. Unlike Array prototype methods like sort()
and reverse()
that are used on the array instance, Object methods are used directly on the Object constructor, and use the object instance as a parameter. This is known as a static method.
This tutorial will go over important built-in object methods, with each section below dealing with a specific method and providing an example of use.
Prerequisites
In order to get the most out of this tutorial, you should be familiar with creating, modifying, and working with objects, which you can review in the “Understanding Objects in JavaScript” article.
For additional guidance on JavaScript in general, you can review our How To Code in JavaScript series.
Object.create()
The Object.create()
method is used to create a new object and link it to the prototype of an existing object.
We can create a job
object instance, and extend it to a more specific object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| const job = { position: "cashier", type: "hourly", isAvailable: true, showDetails() { const accepting = this.isAvailable ? "is accepting applications" : "is not currently accepting applications";
console.log( `The ${this.position} position is ${this.type} and ${accepting}.` ); } };
const barista = Object.create(job);
barista.position = "barista"; barista.showDetails();
|
1 2
| Output The barista position is hourly and is accepting applications.
|
The barista
object now has one property — position
— but all the other properties and methods from job
are available through the prototype. Object.create()
is useful for keeping code DRY by minimizing duplication.
Object.keys()
Object.keys()
creates an array containing the keys of an object.
We can create an object and print the array of keys.
1 2 3 4 5 6 7 8 9 10 11 12
| const employees = { boss: "Michael", secretary: "Pam", sales: "Jim", accountant: "Oscar" };
const keys = Object.keys(employees);
console.log(keys);
|
1
| Output[("boss", "secretary", "sales", "accountant")];
|
Object.keys
can be used to iterate through the keys and values of an object.
1 2 3 4 5 6
| Object.keys(employees).forEach(key => { let value = employees[key];
console.log(`${key}: ${value}`); });
|
1 2 3 4 5
| Output; boss: Michael; secretary: Pam; sales: Jim; accountant: Oscar;
|
Object.keys
is also useful for checking the length of an object.
1 2 3 4
| const length = Object.keys(employees).length;
console.log(length);
|
Using the length
property, we were able to count the 4
properties of employees
.
Object.values()
Object.values()
creates an array containing the values of an object.
1 2 3 4 5 6 7 8 9 10 11 12
| const session = { id: 1, time: `26-July-2018`, device: "mobile", browser: "Chrome" };
const values = Object.values(session);
console.log(values);
|
1
| Output[(1, "26-July-2018", "mobile", "Chrome")];
|
Object.keys()
and Object.values()
allow you to return the data from an object.
Object.entries()
Object.entries()
creates a nested array of the key/value pairs of an object.
1 2 3 4 5 6 7 8 9 10 11
| const operatingSystem = { name: "Ubuntu", version: 18.04, license: "Open Source" };
const entries = Object.entries(operatingSystem);
console.log(entries);
|
1
| Output[["name", "Ubuntu"][("version", 18.04)][("license", "Open Source")]];
|
Once we have the key/value pair arrays, we can use the forEach()
method to loop through and work with the results.
1 2 3 4 5 6 7
| entries.forEach(entry => { let key = entry[0]; let value = entry[1];
console.log(`${key}: ${value}`); });
|
1 2 3 4
| Output name: Ubuntu version: 18.04 license: Open Source
|
The Object.entries()
method will only return the object instance’s own properties, and not any properties that may be inherited through its prototype.
Object.assign()
Object.assign()
is used to copy values from one object to another.
We can create two objects, and merge them with Object.assign()
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const name = { firstName: "Philip", lastName: "Fry" };
const details = { job: "Delivery Boy", employer: "Planet Express" };
const character = Object.assign(name, details);
console.log(character);
|
1 2
| Output {firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
|
It is also possible to use the spread operator (...)
to accomplish the same task. In the code below, we’ll modify how we declare character
through merging the name
and details
objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const name = { firstName: "Philip", lastName: "Fry" };
const details = { job: "Delivery Boy", employer: "Planet Express" };
const character = { ...name, ...details };
console.log(character);
|
1 2
| Output {firstName: "Philip", lastName: "Fry", job: "Delivery Boy", employer: "Planet Express"}
|
This spread syntax in object literals is also known as shallow-cloning.
Object.freeze()
Object.freeze()
prevents modification to properties and values of an object, and prevents properties from being added or removed from an object.
1 2 3 4 5 6 7 8 9 10 11 12 13
| const user = { username: "AzureDiamond", password: "hunter2" };
const newUser = Object.freeze(user);
newUser.password = "*******"; newUser.active = true;
console.log(newUser);
|
1 2
| Output {username: "AzureDiamond", password: "hunter2"}
|
In the example above, we tried to override the password hunter2
with ***, but the password
property remained the same. We also tried to add a new property, active
, but it was not added.
Object.isFrozen()
is available to determine whether an object has been frozen or not, and returns a Boolean.
Object.seal()
Object.seal()
prevents new properties from being added to an object, but allows the modification of existing properties. This method is similar to Object.freeze()
. Refresh your console before implementing the code below to avoid an error.
1 2 3 4 5 6 7 8 9 10 11 12 13
| const user = { username: "AzureDiamond", password: "hunter2" };
const newUser = Object.seal(user);
newUser.password = "*******"; newUser.active = true;
console.log(newUser);
|
1 2
| Output {username: "AzureDiamond", password: "*******"}
|
The new active
property was not added to the sealed object, but the password
property was successfully changed.
Object.getPrototypeOf()
Object.getPrototypeOf()
is used to get the internal hidden [[Prototype]]
of an object, also accessible through the __proto__
property.
In this example, we can create an array, which has access to the Array
prototype.
1 2 3
| const employees = ["Ron", "April", "Andy", "Leslie"];
Object.getPrototypeOf(employees);
|
1 2
| Output [constructor: ƒ, concat: ƒ, find: ƒ, findIndex: ƒ, pop: ƒ, …]
|
We can see in the output that the prototype of the employees
array has access to pop, find, and other Array prototype methods. We can confirm this by testing the employees
prototype against Array.prototype
.
1
| Object.getPrototypeOf(employees) === Array.prototype;
|
This method can be useful to get more information about an object or ensure it has access to the prototype of another object.
There is also a related [Object.setPrototypeOf() method that will add one prototype to another object. It is recommended that you use Object.create()
instead as it is faster and more performant.
Conclusion
Objects have many useful methods that help us modify, protect, and iterate through them. In this tutorial, we reviewed how to create and assign new objects, iterate through the keys and/or values of an object, and freeze or seal an object.