Modelo

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

How to Add Key to Const Object in JavaScript

Oct 05, 2024

In JavaScript, when we declare an object using the 'const' keyword, it means that the reference to the object cannot be changed. However, this does not mean that the object itself is immutable. We can still modify the properties and add new keys to the object without changing its reference. Here's how you can add a key to a const object in JavaScript:

1. Using Object.assign

You can use the Object.assign method to create a new object with the additional key-value pair, without modifying the original const object.

```javascript

const myConstObj = { key1: 'value1' };

const updatedObj = Object.assign({}, myConstObj, { key2: 'value2' });

console.log(updatedObj);

```

In this example, we have created a new object 'updatedObj' with the additional key 'key2' and its value without modifying 'myConstObj'.

2. Using the Spread Operator (...)

Another way to add a key to a const object is by using the spread operator (...) to create a new object with the additional key-value pair.

```javascript

const myConstObj = { key1: 'value1' };

const updatedObj = { ...myConstObj, key2: 'value2' };

console.log(updatedObj);

```

This method also creates a new object 'updatedObj' with the additional key 'key2' and its value without altering 'myConstObj'.

3. Using JSON.parse and JSON.stringify

If the object contains only primitive data types (such as numbers, strings, and booleans), you can also add a key using JSON.parse and JSON.stringify.

```javascript

const myConstObj = { key1: 'value1' };

const updatedObj = JSON.parse(JSON.stringify(myConstObj));

updatedObj.key2 = 'value2';

console.log(updatedObj);

```

This approach creates a deep copy of the original object and then adds the new key-value pair to the copied object.

By using these methods, you can effectively add a key to a const object in JavaScript without violating the rules of const. These techniques allow you to update the object without changing its reference, ensuring the immutability of the const object while still being able to modify its properties.

Recommend