Skip to content

Create an object in JavaScript dynamically | Example code

  • by

In newer JS, you can write the below code (note the square brackets) to create a dynamic object in JavaScript.

var obj = {
    [prop]: Values
};

In older JS this is not available, you would need to do this (still works in new JS as well):

var obj = {};
obj[prop] = Values;

If you want an array of objects as a result, you can initialize an empty array at the top:

var objs = [];

and then push each obj into it:

objs.push(obj);

Alternately, and more readably, you can use the map function:

var objs = MyItems.map(function(item) {
  ...
  return resultObj;
});

Source: stackoverflow.com

Create an object in JavaScript dynamically

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    const age = "Age";
    const mark = "Marks";

    const emp = {
      Name : "John Gik",
      [age] : "57",
      [mark] : "42"
    };

    console.log(emp);

  </script>

</body>
</html> 

Output:

Create an object in JavaScript dynamically

How to create a dynamic object in a loop?

Answer: You can do it using the below code.

<!DOCTYPE html>
<html>
<body>

  <script>

    var objects = {};

    for (var x = 0; x < 5; x++) {
      objects[x] = {name: x};
    }
    console.log(objects);

  </script>

</body>
</html> 

Output:

0: Object { name: 0 }
​
1: Object { name: 1 }
​
2: Object { name: 2 }
​
3: Object { name: 3 }
​
4: Object { name: 4 }

Do comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading