Formatting JavaScript Object to new Array

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to format JavaScript object to new Array −

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>Formatting JavaScript Object to new Array.</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to format the school object to an array</h3>
<script>
   const school = {
      name: "St Marks",
      address: "Delhi",
      students: [
         {
            firstName: "Rohan",
            lastName: "Sharma",
            age: 14,
         },
         {
            firstName: "Mohit",
            lastName: "Singh",
            age: 18,
         },
         {
            firstName: "Mike",
            lastName: "Shaw",
            age: 17,
         },
         {
            firstName: "Roy",
            lastName: "Mehta",
            age: 16,
         },
      ],
   };
   let resEle = document.querySelector(".result");
   let schoolArr = [];
   let { name, address } = school;
   for (let student of school.students) {
      schoolArr.push(
         `${student.firstName} ${student.lastName} ${student.age}`
      );
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      schoolArr.forEach((item) => {
         resEle.innerHTML += item + "<br>";
      });
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 18-Jul-2020 11:43:02
Advertisements