-1

I want to know how to share an array through two HTML files. I have two HTML files and I want to share an array between them. I point out array because for this, I can't use localStorage because it is an array, and I can't use split() because my array has objects in it:

var examplearray = [
 {first: "Nice!", second: "Wonderful!"},
 {first: "Wow!", "Amazing"}
]

I tried linking both of the HTML files to one javascript file, and put the variable there, and alert() the variable to test, but it didn't work. Please show me if there is a way tp share an array between two HTML files.

2 Answers2

0

You need to add two scripts tag to your HTML file. One for JavaScript file to export the array and the other for importing this array to other JavaScript file.

So your HTML file must content this structure:

<script src="/exporting.js"></script>
<script type="module" src="/importing.js"></script>

And your JavaScript file which is exporting the array must contain this statement:

export const array = [1, 2, 3, 4]

Finally the other JavaScript file which will import the array must contain this statement in top level of the file:

import array from '/file/path/exporting.js'
Sujit
  • 1,653
  • 2
  • 9
  • 25
Arda Örkin
  • 121
  • 3
  • 8
0

Instead of an array of objects, use an object of objects. Example:

var exampleObject = {
    0: {first: "Nice!", second: "Wonderful!"},
    1: {first: "Wow!", second: "Amazing!"}
};

This will pretty much work like an array. To get the first object, you do exampleObject[0];


An object can be converted to a string and back to an object whenever you need it.

To convert an object to a string, use JSON.stringify(). Example:

var stringObject = JSON.stringify(exampleObject);

This string can then be stored in your localStorage like this:

localStorage.setItem('exampleObject', JSON.stringify(exampleObject));

To convert the string back to an object, use JSON.parse(). Example:

var myObject = JSON.parse(stringObject);

So, you get the object from your localStorage like this:

var myObject = JSON.parse(localStorage.getItem('exampleObject'));
Sujit
  • 1,653
  • 2
  • 9
  • 25