How to set dynamic property keys to an object in JavaScript?

JavascriptObject Oriented ProgrammingFront End Scripts

Previously it is a two-step process to create a property in an object but the advent of ES6 has made the task very simple. In only one step we can create a property dynamically. Let's discuss it in a nutshell.

Old method(2 step process)

Example

In the following example, the property, instead of declaring in the object itself, is declared outside the object, making it a two-step process.

Live Demo

<html>
<body>
<script>
   let person = 'name';
   let student = {               // step-1
      id: 1,
   };
   student[person] = 'nani';    // step-2
   document.write(JSON.stringify(student));
</script>
</body>
</html>

Output

{"id":1,"name":"nani"}


ES6 Method

Example

In the following example, the property of the object is declared directly in the object itself rather than declaring it outside the object, making it a 1 step process

Live Demo

<html>
<body>
<script>
   let person = 'name';
   let student = {
      id: 1,
      [person] : "nani"
   };
   document.write(JSON.stringify(student));
</script>
</body>
</html>

Output

{"id":1,"name":"nani"}
raja
Published on 30-Jul-2019 09:27:32
Advertisements