
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to change an object Key without changing the original array in JavaScript?
Following is the code to change an object key without changing the original array in JavaScript −
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } </style> </head> <body> <h1>Change an object Key without changing the original array</h1> <button class="Btn">CLICK HERE</button> <h3> Click the above button to change the name object key to fullName </h3> <script> let BtnEle = document.querySelector(".Btn"); let resEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); let obj = [ { name: "Rohan Sharma", age: 12 }, { name: "Shawn Mendes", age: 18 }, { name: "Michael Shaw", age: 15 }, { name: "Mitch Johansson", age: 19 }, ]; BtnEle.addEventListener("click", () => { obj = obj.map((ele) => { ele["fullName"] = ele["name"]; delete ele["name"]; return ele; }); console.log(obj); }); </script> </body> </html>
Output
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button and inspecting the output in console −
- Related Questions & Answers
- De-structuring an object without one key
- Reversing array without changing the position of certain elements JavaScript
- Retrieve key and values from object in an array JavaScript
- Changing an array in place using splice() JavaScript
- JavaScript: How to Create an Object from Key-Value Pairs
- How to access an object value using variable key in JavaScript?
- How to return object from an array with highest key values along with name - JavaScript?
- How to convert an object into an array in JavaScript?
- How to modify key values in an object with JavaScript and remove the underscore?
- Javascript search for an object key in a set
- JavaScript - Convert an array to key value pair
- How to check whether a particular key exist in javascript object or array?
- How to group an array of objects by key in JavaScript
- Change the case without using String.prototype.toUpperCase() in JavaScript
- How to set a String as a key for an object - JavaScript?
Advertisements