Categories
JavaScript Answers

How to Create a Dynamic Object in a Loop with JavaScript?

Spread the love

Sometimes, we want to create a dynamic object in a loop with JavaScript.

In this article, we’ll look at how to create a dynamic object in a loop with JavaScript.

Create a Dynamic Object in a Loop with JavaScript

To create a dynamic object in a loop with JavaScript, we can use the square bracket notation to add properties to an object dynamically.

For instance, we can write:

const objects = {};

for (let x = 0; x < 5; x++) {
  objects[x] = {
    name: 'foo'
  };
}

console.log(objects)

We create an empty object and assign it to the objects variable.

Then we add a for loop that loops through some numbers.

And we use the numbers as property names with objects[x].

Then we assign objects[x] to an object with the name property set to 'foo' as its value.

As a result, we see that the value of objects is:

{
  "0": {
    "name": "foo"
  },
  "1": {
    "name": "foo"
  },
  "2": {
    "name": "foo"
  },
  "3": {
    "name": "foo"
  },
  "4": {
    "name": "foo"
  }
}

from the console log.

Conclusion

To create a dynamic object in a loop with JavaScript, we can use the square bracket notation to add properties to an object dynamically.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to Create a Dynamic Object in a Loop with JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *