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

JavascriptWeb DevelopmentObject Oriented Programming

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 −

raja
Updated on 18-Jul-2020 07:43:56

Advertisements