Replacing array of object property name in JavaScript


Following is the code to replace array of object property name 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;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Replacing array of object property name</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to change the property name of an object in array</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   var person = [
      { name: "Rohan Sharma", age: 16 },
      { name: "Vinit Mehta", age: 18 },
   ];
   person = person.map((item) => {
      return {
         fullName: item.name,
         age: item.age,
      };
   });
   BtnEle.addEventListener("click", () => {
      person.forEach((item) => {
         resEle.innerHTML += "fullName = " + item.fullName + " : Age = " + item.age + "";
      });
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on: 18-Jul-2020

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements