How to use Object.entries() and Array.prototype.forEach() In Javascript
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]) => {
existingObject[key] = value;
});
Example: This example demonstrates how to use Object.entries() and Array.prototype.forEach() to append a new object to an existing object.
let Object1 = {
Name: "Nikunj",
Age: 22,
};
let Object2 = {
Occupation: "Content Writer",
};
Object.entries(Object2).forEach(([key, value]) => {
Object1[key] = value;
});
console.log(Object1);
Output
{ Name: 'Nikunj', Age: 22, 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