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.
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