How to add properties to an object in ES6?

In ES6, there are several ways to add properties to an object.

  1. Use the dot operator (.) to directly add properties to an object. For example:
  2. Create an object with two properties: property1 with value ‘value1’ and property2 with value ‘value2’.
  3. Using square bracket operator([]): You can also use the square bracket operator to add properties to an object. This way allows for dynamically setting property names. For example:
  4. Create an object with two properties: ‘property1’ with the value ‘value1’ and ‘property2’ with the value ‘value2’.
  5. Alternatively, you can use variables to set property names.
  6. An empty object is created with the variable name “obj”. A property called “property1” is dynamically added to the object and assigned the value of “value1”.
  7. By using the Object.defineProperty() method, you can define a new property on an object or modify an existing property. For example:
  8. Create an empty object and define a property ‘property1’ with the value ‘value1’, allowing it to be modified, listed, and configured.
  9. This method also allows for setting properties such as writability, enumerability, and configurability.
  10. By using the Object.assign() method, you can copy one or more source object properties to a target object and return the target object. If the target object already has a property with the same name, the value of the property in the source object will override the value in the target object. For example:
  11. Create an empty object called obj and then assign the properties property1 and property2 with values ‘value1’ and ‘value2’ to it.
  12. This method allows you to add multiple attributes at the same time.

It is important to note that when using the above method to add properties to an object, if the object is a constant (declared using the const keyword), then new properties cannot be added to it. Only existing properties can be modified.

广告
Closing in 10 seconds
bannerAds