How to Create Objects with Dynamic Keys in Javascript ?

Last Updated on :February 26, 2024

In JavaScript, objects typically consist of key-value pairs,there are scenarios where you might need to create objects with dynamic keys. Dynamic keys are determined at runtime and can change based on variables or expressions. In this article, we’ll explore how to create objects with dynamic keys in JavaScript.

Here’s an example of creating objects with dynamic keys using dot notation , bracket notation , Object.defineProperties()

1. Dot Notation

One way to create objects with dynamic keys is by using dot notation. Dot notation allows you to access and assign values to object properties using the dot (.) operator. Here’s an example that demonstrates creating an object with a dynamic key using dot notation:


const dynamicKey1 = "name";
const value1 = "Sanvi";

const dynamicKey2 = "rollno";
const value2 = 5;

const dynamicKey3 = "age";
const value3 = 12;

const student = {};
student[dynamicKey1] = value1;
student[dynamicKey2] = value2;
student[dynamicKey3] = value3;

console.log(student);

{
"name": "Sanvi",    
"rollno": 5,
 "age": 12
}

2. Bracket Notation

Another approach to create objects with dynamic keys using bracket notation. Bracket notation allows you to access and assign values to object properties by enclosing the property name within square brackets ([]). This notation is especially useful when you want to use a variable or an expression as the dynamic key.

Here’s an example illustrating the usage of bracket notation for dynamic keys:


 const dynamicKey1 = "name";
 const value1 = "Sanvi";

 const dynamicKey2 = "rollno";
 const value2 = 5;

 const dynamicKey3 = "age";
 const value3 = 12;

 const student = {
    [dynamicKey1]: value1,
    [dynamicKey2]: value2,
    [dynamicKey3]: value3
 };
 
 console.log(student);

{
    "rollno": 5,
    "name": "Sanvi",
    "age": 12
}

3. Object.defineProperties()

This method is useful for creating dynamic keys on an object


var student = {};

Object.defineProperties(student, {
  'rollno': {
    value: 5,
    writable: true
  },
  'name': {
    value: 'Sanvi',
    writable: true
  },
  'age': {
    value: 12,
    writable: true
  }
});

console.log(student);

{
    "rollno": 5,
    "name": "Sanvi",
    "age": 12
}

Add another property using Object.defineProperty() static method


Object.defineProperty(student, 'school', {
  value: 'DAV Public School',
  writable: false
});

console.log(student);

{
    "rollno": 5,
    "name": "Sanvi",
    "age": 12,
     "school" : "DAV Public School"
}

You may also like...

Leave a Reply

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