How to use object.defineProperty() method In Javascript

The Object.defineProperty() method helps to define a new property in the specified object. To make the newly created property enumerable and writable, we set the `enumerable` and `writable` properties to `true`.

Syntax:

Object.defineProperty(object, property_name, descriptor)

Example: To demonstrate appending new object to the existing object as a key using the Object.defineProperty() method.

Javascript
let Object1 = {
Name: "Poojitha",
Age: 20,
};

let Object2 = {
Occupation: "Content Writer",
};
Object.defineProperty(Object1, "Occupation", {
value: Object2["Occupation"],
enumerable: true,
writable: true,
});

console.log(Object1);

Output
{ Name: 'Poojitha', Age: 20, Occupation: 'Content Writer' }

How to Append an Object as a Key Value in an Existing Object in JavaScript ?

In JavaScript, An object is a key-value pair structure. The key represents the property of the object and the value represents the associated value of the property. In JavaScript objects, we can also append a new object as a Key-value pair in an existing object in various ways which are as follows.

Table of Content

  • Using JavaScript Spread (…) Operator
  • Using JavaScript Object.assign() method
  • Using JavaScript Bracket notation ([])
  • Using JavaScript object.defineProperty() method

Similar Reads

Using JavaScript Spread (…) Operator

The Spread (…) Operator in JavaScript allows to copy all the elements in the existing object into a new object....

Using JavaScript Object.assign() method

The Object.assign() method is used to copy the data from the specified enumerable objects to the target object....

Using JavaScript Bracket notation ([])

The JavaScript bracket notation helps to directly assign the new object as a key-value pair to the existing object....

Using JavaScript object.defineProperty() method

The Object.defineProperty() method helps to define a new property in the specified object. To make the newly created property enumerable and writable, we set the `enumerable` and `writable` properties to `true`....

Using Object.entries() and Array.prototype.forEach()

In this approach, we use the Object.entries() method to get an array of key-value pairs from the new object. Then, we use the Array.prototype.forEach() method to iterate over these pairs and add them to the existing object....