![]() |
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 (…) OperatorThe Spread (…) Operator in JavaScript allows to copy all the elements in the existing object into a new object. Example: Demonstrating appending new object to existing object as a key using the spread operator.
Output { Name: 'Poojitha', Age: 20, Occupation: 'Content Writer' } Using JavaScript Object.assign() methodThe Object.assign() method is used to copy the data from the specified enumerable objects to the target object. Syntax:Object.assign(target_object, source_object) Example: Appending new object to existing object as a key using assign method.
Output { Name: 'Poojitha', Age: 20, Occupation: 'Content Writer' } Using JavaScript Bracket notation ([])The JavaScript bracket notation helps to directly assign the new object as a key-value pair to the existing object. Example: We will create a new key that is similar to the key in the object2 and assign the value to it taken from the object1 by using bracket notation.
Output { Name: 'Poojitha', Age: 20, Occupation: 'Content Writer' } Using JavaScript object.defineProperty() methodThe 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.
Output { Name: 'Poojitha', Age: 20, Occupation: 'Content Writer' } 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. Syntax:Object.entries(newObject).forEach(([key, value]) => { Example: This example demonstrates how to use Object.entries() and Array.prototype.forEach() to append a new object to an existing object.
Output { Name: 'Nikunj', Age: 22, Occupation: 'Content Writer' } |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |