javascript

How to add an object key dynamically in JavaScript


In this article, you will learn about how to add an Object key dynamically in JavaScipt.

JavaScript is the most popular language at this moment and you can do a lot more things by using JavaScript. The main reason because of its popularity is that it can be used both in front-end and back-end. JavaScript comes with a term named Object. In JavaScript Object, you can add a key dynamically. There are several processes to doing so. Let’s see them in the below section. But first, see a basic syntax and example of an Object.

const obj = {
    key1: value,
    key2: value,
    ..........
}

We know that in JavaScript Object there’s key and value exist. You can add a new key to an existing Object and make it dynamic. Though, it is an old way but still useful. Let’s see the below code example:


const studentName = "Deven"

const StudentDetails = {
    'Alex': 24,
    'Gabriel': 22,
}

StudentDetails[studentName] = 21

console.log(StudentDetails)

//Output: { Alex: 24, Gabriel: 22, Deven: 21 }

Here, in the studentDetails object there’s already two name property with their age is exist and we externally add another property into the studentDetails object and you can see in the output that our property has successfully added.

Another way is to perform this action is to simply use the ES6 features. We all know that in ES6, JavaScript comes with some useful changes. You can simply use the key with square brackets which you want to make a key object. see the below code example:


const studentName = "Deven"

let StudentDetails = {
    'Alex': 24,
    [studentName] : 21,
    'Gabriel': 22
}

console.log(StudentDetails)

//Output: { Alex: 24, Deven: 21, Gabriel: 22 }

You can see that in output we add a property in the studentObject by using ES6. These are the ways of how you can add an object key dynamically in JavaScript.

Note: If you are using ES6, it is always recommended to use the second approach.


Share on social media

//