Creation of Large Number of Objects from an Array in JavaScript

Someone wrote this to me:

I'm dealing with an array of arrays that contain personnel data. Here's a simplified example:

const personnelData = [
  ["Lucy", "Smith", 56],
  ["Gary", "Snyder", 34],
];

My goal is to create a Person object for each entry in the array. However, dynamically naming each object within the loop using methods like eval() or window[] is generally considered bad practice.

Since the array could potentially contain hundreds of entries, manually assigning names to objects isn't feasible.

So what is the best way to do this?

Instead of dynamically naming each object, you can create an array of Person objects and populate it with the data from your array of arrays. Here's an example of how you can do it without dynamically naming objects:

class Person {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
}

const personnelData = [
  ["Lucy", "Smith", 56],
  ["Gary", "Snyder", 34],
];
const people = [];

personnelData.forEach((data) => {
  const [firstName, lastName, age] = data;
  const person = new Person(firstName, lastName, age);
  people.push(person);
});

console.log(people);

This code creates a Person class and initializes an array people to store Person objects. Then it iterates over each array within personnelData, extracts the values (firstName, lastName, age), creates a new Person object with those values, and adds it to the people array.

This approach avoids the need for dynamically naming objects and is considered a better practice. It also makes your code more scalable and maintainable, especially when dealing with large datasets.

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda