taho
taho

Reputation: 67

How to import an array file into a javascript file

I want to create a json file in brackets only to store an array that has 200 elements in it, and I want to be able to import that file into my "main.js" file, and be able to use it even though the array itself is not in "main.js" anymore.

How can I do this?

Upvotes: 0

Views: 21779

Answers (5)

Rajani Soni
Rajani Soni

Reputation: 1

Step 1 : add "export" keyword before anything you want to export.

    ex- export const data = [{1,2,3}]

Step 2 : add type="module" in html, where you link your js to html.

    ex-   <script src="index.js" type="module"></script>

Step 3 : add import keyword on top of the file where you want to import data.

    ex- import { data } from './Data.js';

Upvotes: 0

Noman Hassan
Noman Hassan

Reputation: 391

dummyData.js

export const data = [{}, ......, {}];

main.js

import { data } from './dummyData';

if you are using vanilla js, without es6 features, you could do the following:

//dummyData.js

module.exports = [{} ,........, {}];

//main.js

var data = require('./dummyData');

Upvotes: 9

Bibberty
Bibberty

Reputation: 4768

Ok, here is sample: In the demo we will load each object in array and create a paragraph. Because snippet does not support multi files, the working demo is here:

https://repl.it/@PaulThomas1/DemoForTaho

Our HTML:

<div id="content"></div>
<script src="data.js"></script>
<script src="script.js"></script>

Our main javascript (script.js):

document.addEventListener("DOMContentLoaded", function() {

  let contentDiv = document.getElementById("content");
  let template = document.createElement("template");

  data.forEach(dataItem => {
    let element = document.createElement('p');
    element.innerHTML = newPara(dataItem.name);
    contentDiv.appendChild(element);
  });

});

const newPara = (name) => { return `Name: ${name}` };

Our data lives in data.js :

data = [
  {
    "name" : "bert"
  },
    {
    "name" : "bert11"
  },
    {
    "name" : "bert22"
  },
    {
    "name" : "bert33"
  },
    {
    "name" : "bert44"
  },
    {
    "name" : "bert55"
  },
    {
    "name" : "bert66"
  }
];

Upvotes: 0

Shariq
Shariq

Reputation: 506

Create a JS file, say dataProvider.js, have your json defined as a constant, make it global write a function to convert it to JSON and return it, or just return the JSON as-is.

Now in your main.js include the dataProvider.js, and then you can access the shared variable.

Make sure that the page you're loading has both main.js and dataProvider.js imported.

Upvotes: 0

Vikas Verma
Vikas Verma

Reputation: 94

you should first export your json/array from a file file should be something like export const myJsonArray = [{...}, {...}, ...]

then in your main.js you can import the jsonArray like this import myJsonArray from "{file_path}"

Upvotes: 0

Related Questions