Computer >> Computer tutorials >  >> Programming >> Javascript

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


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.

<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

<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"}