In JavaScript, you can use arrays to store collections of data elements, including objects. Objects can be added to an array just like any other data type, such as strings or numbers — and this tutorial will show you how.
What JavaScript Objects Are
First things first. Let’s get the basics out of the way and make sure that, when we talk about “objects,” we’re really talking about one and the same thing.
An “object” in JavaScript is a data structure made up of key-value pairs. You can think of objects as a collection of properties, where each property has a name (the key) and a value. The value can be of any data type, including numbers, strings, arrays, even other, nested objects.
Here’s an example:
let user = {
username: 'johndoe',
firstName: 'John',
lastName: 'Doe',
age: 35
}
In a JavaScript object, the keys are on the left and the values are on the right, delimited by a colon (:
) and, optionally, a leading space. Adjacent key/value pairs are separated by a comma (,
).
Objects are a powerful data structure in JavaScript and are used for many different use cases, including as the data structure for JSON data (note that a JavaScript object and a JSON objects are not the same thing), for organizing related data in an easily accessible way, and for exchanging data between interfaces and programming languages.
Learn more: How to Pass a PHP Array to JavaScript With JSON
How to Store Objects in Arrays
Storing an object in a JavaScript array is not at all that different from storing other data types. Simply use the Array.prototype.push()
method to push the object to the array.
Here’s an example:
// Declare array
let fruits = [];
// Push object
array.push({ name: 'Green Apples', quantity: 500, unit: 'grams' }
Or you could also store the object in a variable before pushing it to the array:
// Declare an array
let fruits = [];
// Declare object
let apples = {
name: 'Green Apples',
quantity: 500,
unit: 'grams'
}
// Push 'apples' object to 'fruits' array
fruits.push(apples);
Once you’ve stored a JavaScript object in an array, you can access the object itself:
console.log(fruits[0]) // {name: 'Green Apples', quantity: 500, unit: 'grams'}
Or its individual properties:
console.log(fruits[0].name) // Green Apples
console.log(fruits[0].quantity) // 500
console.log(fruits[0].unit) // grams
In Summary
The more complex your web app or website gets, the smarter you have to become about the way you use JavaScript’s built-in capabilities to capture and work with data. And storing objects in arrays is one of those capabilities.
Thank you for reading this far, and I hope this tutorial helped you learn what you needed to learn. If you have any questions, or if you’d like to share any tips and tricks of your own with the rest of this post’s readers, leave a reply below!
Learn this next: How to Search for Objects in JavaScript Arrays of Objects