Syntax error Can we convert two arrays into one JavaScript object?

Can we convert two arrays into one JavaScript object?



Following is the code to convert two arrays into one JavaScript object −

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,.sample {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
   .result {
      color: red;
   }
</style>
</head>
<body>
<h1>Convert two arrays into one JavaScript object</h1>
<div class="sample">
["firstName", "lastName", "age"]<br />["Rohan", "Sharma", 21]
</div>
<div class="result"><br /></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to create an object from the above two arrays</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   var objKeys = ["firstName", "lastName", "age"];
   var objValues = ["Rohan", "Sharma", 21];
   var resultObj = {};
   BtnEle.addEventListener("click", () => {
      objKeys.forEach(
         (element, index) => (resultObj[element] = objValues[index])
      );
      for (let i in resultObj) {
         resEle.innerHTML += "Key = " + i + " : Value = " + resultObj[i] + "<br>";
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on: 2020-07-21T07:26:34+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements