Modelo

  • EN
    • English
    • Español
    • Français
    • Bahasa Indonesia
    • Italiano
    • 日本語
    • 한국어
    • Português
    • ภาษาไทย
    • Pусский
    • Tiếng Việt
    • 中文 (简体)
    • 中文 (繁體)

How to Add Keys to a Const Object in JavaScript

Oct 06, 2024

When working with JavaScript, you may come across situations where you need to add a new key to a const object. While const ensures that the variable itself cannot be reassigned, it does not prevent modifications to the object's properties. Therefore, it is possible to add new keys to a const object without violating its immutability. Here are a few techniques to achieve this:

1. Using Object.assign:

Object.assign can be used to create a new object by merging the properties of existing objects. By creating a new object with the additional key and merging it with the original object, you can effectively add a new key to a const object.

```javascript

const originalObject = { key1: 'value1' };

const newKey = 'key2';

const valueForNewKey = 'value2';

const updatedObject = Object.assign({}, originalObject, { [newKey]: valueForNewKey });

```

2. Using the spread operator:

The spread operator (...) can also be used to create a new object with the additional key. By spreading the properties of the original object and adding the new key-value pair, a new object with the updated properties can be created.

```javascript

const originalObject = { key1: 'value1' };

const newKey = 'key2';

const valueForNewKey = 'value2';

const updatedObject = { ...originalObject, [newKey]: valueForNewKey };

```

3. Using Object.defineProperty:

Object.defineProperty allows you to add a new property to an object, or modify an existing one, with a specified configuration. This method allows for fine-grained control over the added property.

```javascript

const originalObject = { key1: 'value1' };

const newKey = 'key2';

const valueForNewKey = 'value2';

Object.defineProperty(originalObject, newKey, {

value: valueForNewKey,

writable: true,

enumerable: true,

configurable: true

});

```

These techniques provide different ways to add new keys to a const object in JavaScript without violating its immutability. They allow you to work with const objects while still being able to update and modify their properties as needed.

Recommend