How to change an object Key without changing the original array in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to change an object key without changing the original array in JavaScript −

Example

 Live Demo

<!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 −

raja
Published on 18-Jul-2020 09:08:33
Advertisements