This content originally appeared on Envato Tuts+ Tutorials and was authored by Kingsley Ubah
In this article, we'll go through the various ways to iterate over the properties of an object in JavaScript.
What is an Object in JavaScript?
An object is a special data collection in a programming language such as JavaScript—it's used to represent real-world objects, or to store program state or organize program data. An object could have one or more properties to describe it, and may also have methods for performing common tasks.
For example, a bank account can be thought of as an object, with properties like bank balance, account type and account currency all describing the bank account.
Tasks like subtracting from or adding money to the account, closing the account and sending money from the account can all be represented as methods.
The most popular way to represent an object in JavaScript is with double curly brackets (aka object literals). On the object, we can define properties, methods or both.
const bankAccount = { balance: 100, currency: "USD", type: "savings", subtract: function(expenses) { const newBal = this.balance - expenses this.balance = newBal } }
Each object property consists of the property accessor (eg. currency
) and the property value (eg "USD"
). Methods are functions which perform specific tasks within the object.
Inside the subtract
method which subtracts the new expense from the bank balance, we accessed the balance property using this
. We can access any property or method from within the object using the this
reference.
We can also iterate over the properties of the object to process them one by one. In simple terms, iteration is the process of repeating certain algorithmic steps until a particular condition is met. This is often called a loop. In this case, iteration over a data set means to run some code for each item in the set.
Let's take a look at some of the modern ways to iterate over an object's properties in JavaScript.
Iterate Over Property Keys with Object.keys()
Object.keys()
returns an array containing the keys of all properties on any given object.
const user = { name: "Kingsley", age: 28, job: "Web Developer" } console.log(Object.keys(user)); // ["name", "age", "job"]
So we can combine Object.keys()
with a for
loop to iterate over all the properties of an object by iterating over its keys like so:
const user = { name: "Kingsley", age: 28, job: "Web Developer" } for (const key of Object.keys(user)) { console.log(`${key} = ${user[key]}`) } /* "name = Kingsley" "age = 28" "job = Web Developer" */
Because our iterator gives us the keys to the object properties, we are able to access the values directly from the object user
using the property accessor syntax: user[key]
.
Directly Iterate Over Property Values with Object.values()
Object.values()
works in a very similar way to Object.key()
. The main difference between the two is that while Object.keys()
returns just the property keys, Object.values()
returns the values instead.
Consider the following code which returns only the values for all properties:
const user = { name: "Kingsley", age: 28, job: "Web Developer" } console.log(Object.values(user)) // ["Kingsley", 28, "Web Developer"]
Using a for
loop, iterate over the properties of an object with Object.values()
.
const user = { name: "Kingsley", age: 28, job: "Web Developer" } for (const value of Object.values(user)) { console.log(`value = ${value}`) } /* "value = Kingsley" "value = 28" "value = Web Developer" */
Because the property keys are going to be required in many cases, this is probably not the method you'd want to use when iterating over an object.
Iterate over Object Properties with Object.entries()
Object.entries()
provides a cleaner way to access both the keys and values of any given object within a JavaScript loop.
The method returns a multidimensional array (aka an array of arrays) for any given object. Each child array contains both the key and value for a particular property.
const user = { name: "Kingsley", age: 28, job: "Web Developer" } console.log(Object.entries(user)) // [["name", "Kingsley"], ["age", 28], ["job", "Web Developer"]]
Now we can use Object.entries()
with a for loop to easily retrieve both key and value for each property like so:
const user = { name: "Kingsley", age: 28, job: "Web Developer" } for (const entry of Object.entries(user)) { console.log(`${entry[0]} = ${entry[1]}`) } /* "name = Kingsley" "age = 28" "job = Web Developer" */
Here, for every entry, we find the entry value at index 1 and the key at index 0.
To further simplify the code, we can use array destructuring to retrieve the key and value for each property into separate variables:
for (const [key, value] of Object.entries(user)) { console.log(`${key} = ${value}`) } // gives the same output as the last code block
Compared to the other methods, this approach is much cleaner and readable.
Conclusion
Object.entries()
is the recommended method for iterating over an object's properties in JavaScript.
Since the method returns a multidimensional array, we can greatly simplify our code by using the array destructuring syntax to retrieve each property into a separate variable. This helps in keeping everything flexible.
Object.values()
could be used in cases where you only need the values and not the keys.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Kingsley Ubah
Kingsley Ubah | Sciencx (2022-01-11T13:05:20+00:00) How To Iterate Over Object Properties in JavaScript. Retrieved from https://www.scien.cx/2022/01/11/how-to-iterate-over-object-properties-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.