Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
<!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 −

Advertisements