Modelo

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

How to Add a Key to a Const Object in JavaScript

Oct 09, 2024

In JavaScript, a const object is an object whose reference cannot be reassigned, but the properties of the object can be modified. If you have a const object and you need to add a new key to it, you can use the Object.assign() method or the spread operator to achieve this without violating the const status of the object.

Using Object.assign():

You can use the Object.assign() method to create a new object that combines the properties of the original const object with the new key-value pair. Here's an example:

const myConstObj = {key1: 'value1', key2: 'value2'};

const modifiedObj = Object.assign({}, myConstObj, {newKey: 'newValue'});

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

In this example, we create a new object called modifiedObj by using Object.assign() to merge myConstObj with the new key-value pair {newKey: 'newValue'}. Notice that we pass an empty object {} as the first argument to Object.assign() to create a new object instead of modifying the original const object.

Using the spread operator:

Alternatively, you can use the spread operator (...) to achieve the same result. Here's how to do it:

const myConstObj = {key1: 'value1', key2: 'value2'};

const modifiedObj = {...myConstObj, newKey: 'newValue'};

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

In this example, we create a new object called modifiedObj by spreading the properties of myConstObj and adding the new key-value pair {newKey: 'newValue'}.

Remember that both methods create a new object with the added key while leaving the original const object unchanged. This allows you to add keys to a const object without violating its immutability.

In conclusion, you can add a new key to a const object in JavaScript by using Object.assign() or the spread operator to create a new object with the additional key-value pair. This technique allows you to modify the contents of a const object without reassigning its reference and breaking the const status. Thank you for reading and happy coding!

Recommend