Object.assign() method
The Object.assign() method is a built-in function in JavaScript that is used to merge the properties of multiple source objects into a target object. It creates a new object or modifies an existing object by copying the properties from one or more source objects to the target object.
Syntax:
Object.assign(target, ...sources)
Example: In this example, we are using the above-explained approach.
// Source objects
const person = {
name: "Nikita",
age: 30,
};
const address = {
city: "Haldwani",
state: "Uttarakhan",
};
// Creating a new object and merging properties using Object.assign()
const mergedObject = Object.assign({}, person, address);
console.log(mergedObject);
Output
{ name: 'Nikita', age: 30, city: 'Haldwani', state: 'Uttarakhan' }
How to create object properties in JavaScript ?
JavaScript is built on an object-oriented framework. An object is a collection of properties, where each property links a key to a value. These properties are not in any specific order.
The value of a JavaScript property can be a method (function). Object properties can be updated, modified, added, or deleted. Sometimes, properties are static and cannot be changed. In this article, we will explore how to access and create object properties in JavaScript.
There are several methods that can be used to create object properties.
Table of Content
- Approach 1: Using the dot operator
- Approach 2: Using Square Bracket Notation
- Approach 3: Object Initializer (Literal) Syntax
- Approach 4: Object.assign() method
- Approach 5: Using the Spread operator
- Approach 6: Using the Object.defineProperties() method