How to import an Object with Sub Objects and Arrays in JavaScript?


Following is the code for importing an object with Sub objects and arrays 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;
   }
</style>
</head>
<body>
<h1>Importing an Object with Sub Objects and Arrays</h1>
<div class="result" style="color: green;"></div>
<script>
let sampleEle = document.querySelector(".sample");
let obj = JSON.parse(sampleEle.innerHTML);
</script>
<script src="script.js" type="module">
</script>
</body>
</html>

script.js

import obj from "./sample.js";
let resultEle = document.querySelector(".result");
for (let i in obj) {
   resultEle.innerHTML += "Property = " + i + " : Value = " + obj[i] + "";
}

sample.js

export default{
   firstName: "Rohan",
   lastName: "Sharma",
   school: {
      name: "St Marks",
      address: "USA",
   },
   sports: ["cricket", "football"],
};

Output

The above code will produce the following output −

Updated on: 18-Jul-2020

469 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements