close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than what’s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

Create Array of Objects JavaScript: Best Practices

Create Array of Objects JavaScript: Best Practices
Author
Nimrod Kramer
Related tags on daily.dev
toc
Table of contents
arrow-down

🎯

Learn the best practices for creating arrays of objects in JavaScript. Understand how to use arrays and objects efficiently, handle serialization with JSON, and practice array manipulation techniques.

Creating an array of objects in JavaScript is a powerful way to organize and manage data. This approach allows you to group related data together, making your code more understandable and easier to maintain. Here are the key takeaways:

  • Why Use Arrays of Objects: They keep related data together, are easy to iterate over, and flexible for data manipulation.
  • Arrays: Use them to hold a list of values, including objects. Remember to use square brackets [] for creation and know that they can hold multiple data types.
  • Objects: Ideal for detailed information storage with key-value pairs. Access them using dot or bracket notation.
  • Best Practices: Use array literals, implement trailing commas, avoid non-numeric properties, embrace destructuring, and handle objects within arrays carefully.
  • Array Manipulation: Focus on readability, proper return statements in callbacks, and modern loop constructs.
  • Serialization with JSON: Use JSON.stringify and JSON.parse for data transfer.

Exercises: Practice by creating a list of car objects, filtering for specific criteria, managing a to-do list, and handling a book collection.

By following these guidelines and engaging in hands-on activities, you'll enhance your skills in creating and managing arrays of objects in JavaScript.

Arrays

Arrays in JavaScript let you keep a bunch of values under one name. Think of them as a list where you can line up things you’re related to, like items in a shopping list or names in a guest list. They help you keep stuff organized and make it easy to look through them.

Here’s what you should know about arrays:

  • Arrays keep values in a specific order, each with its own number starting from 0.

  • You make an array using square brackets [] and put your items inside, separated by commas:

let fruits = ['apple', 'banana', 'orange'];
  • Arrays can hold different types of things - words, numbers, true or false values, objects, and even other arrays.

  • Arrays come with handy tools like .push() and .pop() to add or remove items.

  • You can also use loops and methods like .map(), .filter(), .reduce() to go through arrays and change or pick out what you need.

Basically, arrays give you a neat way to group and work with a bunch of related data in your JavaScript projects.

Objects

While arrays help you list things in order, objects are for when you want to store information that comes in pairs - like a name and its value. They are great for when you want to describe something with more detail, like a user’s profile or a product’s features.

For example:

let user = {
  firstName: 'John',
  lastName: 'Doe',
  email: 'john@doe.com'
};

You can get to the information in objects using dot notation like user.firstName or square bracket notation like user['email'].

Important things about objects:

  • They can have different types of info as their values - words, numbers, true or false values, lists, and even functions.

  • You can also put objects inside other objects, making your data structure more complex.

  • Objects can change; you can add more info to them whenever you need.

In short, objects let you create a detailed model of real-world things, making your code more clear and organized.

Best Practices for Creating Arrays of Objects

1. Use Array Literals

When making arrays in JavaScript, it's best to use the simple square bracket way instead of the Array constructor.

For example:

// Array literal
const fruits = ['apple', 'banana', 'orange']; 

// Array constructor 
const vegetables = new Array('tomato', 'spinach', 'carrot');

Using square brackets is shorter and clearer. The Array constructor can be tricky, especially if you use it with just one number, because it makes an array of that length, not an array with one element.

Sticking to square brackets makes your code easier to understand and less likely to have bugs.

2. Implement Trailing Commas

It's a good idea to put a comma after the last item in your array.

For example:

const fruits = [
  'apple',
  'banana',
  'orange',
];

This makes it easier to add or take away items later because you won't have to change the last line if it already has a comma. It also makes your changes clearer when you're looking at version history, and helps avoid simple mistakes like forgetting to add a comma.

In short, trailing commas make it easier to keep your arrays up to date.

3. Avoid Non-Numeric Properties

Arrays should really just use numbers for their items. Adding other types of properties can be confusing.

For example:

const fruits = [];
fruits.name = 'Fruit Basket'; // non-numeric property

If you need to use names or other types of keys, consider using Maps instead. They're made for this kind of thing.

Keeping arrays simple and to the point helps keep your code clean. Use Objects or Maps for more complex needs.

4. Embrace Destructuring

Destructuring is a neat way to pull out values from arrays (or objects) and put them into their own variables.

For example:

const point = [10, 25];

// Without destructuring
const x = point[0]; 
const y = point[1];

// With destructuring
const [x, y] = point; 

This makes your code neater and easier to read, especially when you're dealing with lots of values. It's also handy when you're using array methods like .map() and .filter().

In general, destructuring makes it easier to work with arrays without having to keep track of each item's index. It's worth using whenever you can to make your code simpler.

Handling Objects within Arrays

1. Getter and Setter Pairs

When you have objects in an array, using getter and setter methods helps you safely look at and change the object's properties. Getters let you see a property's value, and setters let you change it.

Here's a quick example:

let users = [
  {
    _firstName: 'John',
    get firstName() {
      return this._firstName;
    },
    set firstName(name) {
      this._firstName = name;
    }
  },
  {
    _firstName: 'Jane',
    get firstName() {
      return this._firstName; 
    },
    set firstName(name) {
      this._firstName = name;
    }
  }
];

Now, you can easily get and change the firstName of anyone in the list like this:

users[0].firstName; // Shows John's firstName
users[1].firstName = 'Maria'; // Changes Jane's firstName to Maria

The big pluses here are:

  • Privacy and control - You can check and set values safely.
  • Uniformity - It gives a standard way to access properties.
  • Extra features - You can do more when getting or setting values.

So, using getters and setters makes your code neater and managing properties easier.

2. Object Mutability

Objects in JavaScript arrays can change, or in other words, they're mutable. This means you can update their values anytime.

For instance:

let users = [{ name: 'John' }, { name: 'Jane' }];

users[0].name = 'Bob'; // Changes John's name to Bob

This can lead to:

  • Unexpected changes - Parts of your program might change an object without you knowing.
  • Possible bugs - If your code expects an object to stay the same, changes can cause problems.
  • Being careful - You need to think about who can change your objects.

To manage this, you can:

  • Copy safely - Use .slice(), ...spread, Object.assign() to make copies.
  • Lock objects - Object.freeze() stops any changes.
  • Watch who gets in - Make sure only certain parts of your code can change objects.

Basically, being able to change objects is useful but be careful to avoid issues.

3. Proper Property Access

There are a few ways to get to the properties of objects in an array:

Dot notation

users[0].name

Bracket notation

users[0]['name']

Optional chaining

users[0]?.name

Here's when to use each:

  • Dot notation is easy and clean for known properties.
  • Brackets are good for properties with changing names.
  • Optional chaining helps avoid errors when a property might not be there.

So, pick the right method based on what you're doing. It helps keep your code tidy and reduces mistakes.

Array Manipulation Techniques

1. Line Breaks and Spaces for Readability

When dealing with big arrays, adding line breaks and spaces can make your code easier to read. Here's how:

const fruits = [
  'apple', 
  'banana',
  'orange'
];

const vegetables = [ 'tomato', 'spinach', 'carrot' ];

The fruits array is simpler to look at. This approach is also helpful when you're using methods like .map(), .filter(), etc:

const tastyFruits = fruits.filter(fruit => {
  return [
    'apple',
    'orange'
  ].includes(fruit); 
});

Just remember not to add spaces inside the brackets to avoid errors. Keeping your arrays organized this way makes your code clearer.

2. Return Statements in Callbacks

When you're using array methods like .map(), .reduce(), and .filter(), make sure to return the result you want:

// Not the best way
fruits.map(fruit => {
  fruit.toUpperCase();  
});

// A better way
fruits.map(fruit => {
  return fruit.toUpperCase(); 
});

This ensures you actually get what you expect. Missing the return can cause tricky bugs. Always returning in callbacks is a good habit.

3. Modern Loop Constructs

For looping through arrays, opt for modern ways like .forEach, .map(), .filter(), and for...of instead of the old for and while loops.

For instance:

// Not the best way
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// A better way
for (const fruit of fruits) {
  console.log(fruit); 
}

These newer methods are neater and take care of things like scope automatically. They also clearly show that you're working with an array. Using them can make your code cleaner.

sbb-itb-bfaad5b

Serialization with JSON

JSON (JavaScript Object Notation) is a simple way to turn JavaScript data, like arrays of objects, into a string that can be saved or sent around easily.

Here's what you need to know about JSON:

  • It looks a lot like regular JavaScript but needs double quotes around property names and doesn't allow functions or comments.
  • JavaScript has JSON.stringify to turn data into a JSON string and JSON.parse to turn the string back into data.
  • JSON strings are compact and easy to move between different parts of a program or even different programs.

For example, turning an array of objects into JSON and back looks like this:

const data = [
  {name: "John", age: 30}, 
  {name: "Sarah", age: 25}
];

// Convert to JSON string
const json = JSON.stringify(data); 

// json is now:
// '[{"name":"John","age":30},{"name":"Sarah","age":25}]'

// Convert back to JavaScript value
const parsed = JSON.parse(json); 

// parsed has the original data

Using JSON.stringify, we can turn any JavaScript value into a JSON string. This can be useful for saving data, sending it to a server, or sharing it with other programs.

When we need our data again, JSON.parse changes the JSON string back into JavaScript.

Why use JSON? It's easy to share data across different programs, it saves space, and it's easy to read.

In short, JSON is a handy way to serialize JavaScript objects and arrays into a format that's easy to use, store, and share. With JSON.stringify and JSON.parse, switching between JavaScript and JSON is straightforward.

Summary

Best Practices for Arrays of Objects

When you're working with arrays of objects in JavaScript, it's like organizing a room. You want to keep things tidy and know where everything is. Here's what you should remember:

Use arrays and objects smartly

  • Group similar items into objects, and then put these objects into arrays.
  • Use handy tools like .map() and .filter() to work with your data.
  • Keep in mind that objects inside arrays can change when you least expect it.

Stick to best practices

  • Choose simple square brackets to make arrays.
  • Add a comma after the last item in your array to make adding or removing items easier.
  • Use numbers for your array indexes.
  • Break down arrays into individual pieces with destructuring to keep things simple.
  • Use getter and setter methods to safely access and update your data.
  • Be careful with how you access properties.

Make your code easy to read

  • For long arrays, spread them out over a few lines.
  • Always use return statements in your array callbacks.
  • Opt for modern ways to loop through arrays, like .forEach and for..of.
  • Turn your array data into a string with JSON when you need to save or send it somewhere.

The main idea is to use arrays and objects to keep your data organized. By following modern practices and using the tools JavaScript offers, you can write code that's easy to manage. Getting good with arrays and objects will help you write better programs that are easier to update and maintain.

Exercises

Here are some hands-on activities to help you practice what you've learned about making and using arrays of objects in JavaScript:

Exercise 1

Create a list of car objects with details like brand, model, year, and color. Then, use a loop to go through the list and print out each car's model and year.

Exercise 2

Using the list of cars you made in Exercise 1, use .filter() to make a new list that only includes the red cars. Then, use .map() to make a list of strings that show the brand and model of each car.

Exercise 3

Make a list for to-do items where each item has a title, how important it is (priority), whether it's done (completed), and when it was made (createdDate). Write functions to add new items, remove items, and show all the important things that aren't done yet.

Exercise 4

Start with an empty list. Create four objects for different books, including details like title, author, number of pages, and whether you've read them. Add these book objects to your list.

Exercise 5

Take your list of books from Exercise 4. Write a function that returns a new list, leaving out any books that are over 500 pages long.

The main skills to practice are:

  • Making lists of objects
  • Using loops, .filter(), and .map() with lists of objects
  • Adding and removing objects from lists safely
  • Working with properties of objects in lists

By doing exercises like these, you'll get more comfortable with combining arrays and objects.

Related posts

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more