How to use Object.assign() In Javascript
This method allows you to copy the properties of one or more source objects to a target object.
Syntax:
Object.assign(target, ...sources);
Example: In this example, we have used Object.assign() method.
// Sample object
let myObject = { oldKey: "value" };
// Rename the key using Object.assign()
let renamedObject = Object.assign({}, { newKey: myObject.oldKey });
console.log(renamedObject);
Output
{ newKey: 'value' }
Rename Object Key in JavaScript
In JavaScript, objects are used to store the collection of various data. It is a collection of properties. A property is a âkey: valueâ pair where Keys are known as âproperty nameâ and are used to identify values. Since JavaScript doesnât provide an inbuilt function to rename an object key. So we will look at different approaches to accomplish this.
Below are the different approaches to rename Object key in JavaScript:
Table of Content
- Assignment of variable
- Using defineProperty()
- Using Object.assign()
- Object Destructuring with spread operator
- Using a temporary variable and delete
Contact Us