How to Append an Object as a Key Value in an Existing Object in JavaScript ?
Last Updated :
30 Jan, 2024
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.
Using JavaScript Spread (…) Operator
The 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.
Javascript
let Object1 = {
Name: "Poojitha" ,
Age: 20,
};
let Object2 = {
Occupation: "Content Writer" ,
};
Object1 = {
...Object1,
...Object2,
};
console.log(Object1);
|
Output
{ Name: 'Poojitha', Age: 20, Occupation: 'Content Writer' }
Using JavaScript Object.assign() method
The 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.
Javascript
let Object1 = {
Name: "Poojitha" ,
Age: 20,
};
let Object2 = {
Occupation: "Content Writer" ,
};
Object.assign(Object1, Object2);
console.log(Object1);
|
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.
Javascript
let Object1 = {
Name: "Poojitha" ,
Age: 20,
};
let Object2 = {
Occupation: "Content Writer" ,
};
Object1[ "Occupation" ] = Object2[ "Occupation" ];
console.log(Object1);
|
Output
{ Name: 'Poojitha', Age: 20, Occupation: 'Content Writer' }
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`.
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' }
Share your thoughts in the comments
Please Login to comment...