Modelo

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

Adding a Key to a Const Object in JavaScript

Oct 15, 2024

Are you working on a project where you need to add a new key to a const object in JavaScript? While it is common knowledge that const objects cannot be re-assigned, it is still possible to add new keys to them without breaking the immutability. Let's explore how you can achieve this.

One way to add a key to a const object is by using the object spread syntax introduced in ES6. When you want to add a new key to a const object, you can create a new object by spreading the original object and then assigning the new key-value pair. Here's an example of how to do this:

```javascript

const originalObject = {

key1: 'value1',

key2: 'value2'

};

const updatedObject = {

...originalObject,

newKey: 'newValue'

};

console.log(updatedObject); // { key1: 'value1', key2: 'value2', newKey: 'newValue' }

```

In this example, we create a new object `updatedObject` by spreading the `originalObject` and adding a new key `newKey` with the value `'newValue'`. This way, we are not modifying the original const object, but rather creating a new object with the updated key.

Another method to add a key to a const object is by using the Object.assign() method. This method can be used to copy the values of all enumerable own properties from one or more source objects to a target object. Here's how you can use Object.assign() to add a new key to a const object:

```javascript

const originalObject = {

key1: 'value1',

key2: 'value2'

};

const updatedObject = Object.assign({}, originalObject, { newKey: 'newValue' });

console.log(updatedObject); // { key1: 'value1', key2: 'value2', newKey: 'newValue' }

```

In this example, we create a new object `updatedObject` by using Object.assign() to merge the `originalObject` with a new object containing the new key-value pair. This creates a new object without modifying the original const object.

It's important to note that while these methods allow you to add new keys to a const object, they do not change the immutability of the original object. The original const object remains unchanged, and a new object with the updated key is created.

In conclusion, adding a key to a const object in JavaScript is possible without breaking its immutability. By using the object spread syntax or the Object.assign() method, you can create a new object with the added key without modifying the original const object. This allows you to work with const objects in a flexible and efficient manner.

Recommend