JavaScript Array of Objects Tutorial – How to Create, Update, and Loop Through Objects Using JS Array Methods

In JavaScript, an array of objects is a powerful data structure that allows you to store and manipulate collections of related data. Each object in the array represents a single entity with its own properties and values. This makes arrays of objects ideal for representing real-world data like lists of products, users, or any other items that share common attributes.

In this comprehensive tutorial, we‘ll dive deep into working with arrays of objects in JavaScript. You‘ll learn how to create arrays of objects, access and update object properties, add and remove objects from arrays, loop through object collections, search and filter arrays, transform object data, sort arrays based on object properties, and more. Let‘s get started!

Creating an Array of Objects

To create an array of objects in JavaScript, use square brackets [] to define the array and curly braces {} to define each object within the array. Here‘s an example that creates an array of objects representing products in an online store:

let products = [
  {
    id: 1,
    name: "Wireless Bluetooth Headphones", 
    price: 49.99,
    category: "Electronics",
    inStock: true
  },
  {
    id: 2,
    name: "Stainless Steel Water Bottle",
    price: 14.95, 
    category: "Kitchen",
    inStock: true
  },
  {
    id: 3,
    name: "Organic Cotton T-Shirt",
    price: 24.99,
    category: "Apparel", 
    inStock: false    
  }
];

Each object in the products array represents a product with properties like id, name, price, category, and inStock. The objects are separated by commas.

Accessing and Updating Object Properties

Once you have an array of objects, you can access and update the properties of individual objects using dot notation or bracket notation.

To access an object property using dot notation, use the object variable name followed by a dot and the property name:

console.log(products[0].name); // "Wireless Bluetooth Headphones"
console.log(products[1].price); // 14.95

To access a property using bracket notation, use the object variable name followed by the property name in brackets and quotes:

console.log(products[0]["category"]); // "Electronics" 
console.log(products[2]["inStock"]); // false

Updating an object property works the same way:

products[0].price = 39.99;
products[1]["inStock"] = false;

console.log(products[0].price); // 39.99
console.log(products[1].inStock); // false

Adding and Removing Objects

JavaScript provides several built-in methods for adding and removing objects from arrays.

To add an object to the end of an array, use the push() method:

products.push({
  id: 4,  
  name: "Leather Wallet",
  price: 29.99,
  category: "Accessories",
  inStock: true
});

To add an object to the beginning of an array, use unshift():

products.unshift({
  id: 0,
  name: "USB Charging Cable",
  price: 9.99,
  category: "Electronics", 
  inStock: true
});

To add or remove objects at a specific array index, use splice():

// insert object at index 2
products.splice(2, 0, {
  id: 2.5,
  name: "Insulated Travel Mug", 
  price: 17.50,
  category: "Kitchen", 
  inStock: true
});

// remove 1 object starting at index 3
products.splice(3, 1);

To remove an object from the end of an array, use pop():

products.pop(); // removes last object

And to remove an object from the start of an array, use shift():

products.shift(); // removes first object

Looping Through Objects

Looping through an array of objects is a common task. JavaScript provides several ways to iterate through arrays.

The classic for loop syntax works by initializing a counter, specifying a condition to check each iteration, and incrementing the counter:

for(let i = 0; i < products.length; i++) {
  console.log(products[i].name);
}

A more modern syntax is the for...of loop which iterates through the array objects directly:

for(let product of products) {
  console.log(product.name);  
}

To get the index and object, use for...in with Object.entries():

for(let [index, product] of Object.entries(products)) {
  console.log(index, product.name);
}

Another option is the forEach() method which accepts an inline callback function to execute on each array element:

products.forEach(product => {
  console.log(product.name);
});

Searching and Filtering Objects

To search for an object in an array by its properties, use the find() method:

let result = products.find(product => product.id === 2);
console.log(result.name); // "Stainless Steel Water Bottle"

To get an array of all matching objects, use filter():

let kitchen = products.filter(product => product.category === "Kitchen");
console.log(kitchen); // [{...}, {...}]

Transforming Object Data

To create a new array of objects transformed using a mapper function, use map():

let productNames = products.map(product => product.name);
console.log(productNames); // ["Wireless Bluetooth Headphones", "Stainless Steel Water Bottle", ...]

Sorting Objects

To sort an array of objects based on a compare function, use sort():

let sortedProducts = products.sort((a, b) => a.price - b.price);
console.log(sortedProducts); // objects sorted by price ascending

Use b - a to sort descending.

Checking Object Conditions

To check if all objects meet a condition, use every():

let allInStock = products.every(product => product.inStock);
console.log(allInStock); // are all products in stock? true/false

To check if at least one object meets a condition, use some():

let hasElectronics = products.some(product => product.category === "Electronics");  
console.log(hasElectronics); // are any products electronics? true/false

Shopping Cart Example

Let‘s solidify these concepts with a more advanced e-commerce example. Imagine we have a shopping cart array storing products that have been added by a customer:

let cart = [
  {
    productId: 1,
    name: "Wireless Bluetooth Headphones",
    price: 49.99,
    quantity: 1    
  },
  {  
    productId: 3,
    name: "Organic Cotton T-Shirt", 
    price: 24.99,
    quantity: 2
  }
];

To add a new product object to the cart, we could use push() or unshift() like before. But we also need to check if the product already exists in the cart, in which case we should update the quantity instead of duplicating the object.

Here‘s how we could write an addToCart function to handle this:

function addToCart(productId, name, price, quantity = 1) {
  let existingProduct = cart.find(item => item.productId === productId);

  if(existingProduct) {
    existingProduct.quantity += quantity;
  } else {
    cart.push({
      productId,
      name, 
      price,
      quantity 
    });
  }
}

addToCart(1, "Wireless Bluetooth Headphones", 49.99);
addToCart(2, "Stainless Steel Water Bottle", 14.95, 3);

console.log(cart);

The find() method checks if a matching productId already exists before deciding whether to update quantity or add a new object.

To calculate the cart total, we can loop through and multiply price * quantity, adding the total for each product:

function getCartTotal() {
  let total = 0;

  for(let item of cart) {
    total += item.price * item.quantity;  
  }

  return total;
}

console.log(getCartTotal()); // 119.84

To empty the cart, we can set the array to an empty array literal:

cart = [];

Performance Considerations

When working with large arrays of objects, be mindful of performance. Searching, filtering, and transforming large arrays can be computationally intensive, so avoid doing so unnecessarily.

Initialize arrays with a pre-defined size if possible to avoid dynamic re-allocation. Use for loops instead of forEach and other methods for faster looping. Avoid deeply nested arrays and objects. Breakdown complex transformations into smaller, simpler pieces. Consider using a library like Lodash for certain use cases.

Summary

JavaScript arrays of objects are fantastically powerful for modeling and manipulating structured data. In this tutorial, we covered everything you need to know to create, update, add, remove, search, filter, transform, and loop through arrays of objects using built-in JavaScript methods.

I hope this knowledge serves you well in your JavaScript endeavors! Let me know if you have any other questions.

Similar Posts