Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export array to be used in another javascript file

In my post request, I want to check if thisString exists in another javascript file array.

Array.js

exports.names = [
    'John',
    'Mary'
]

Main.js

if (names.includes(thisString)) {
    ...do stuff...
}

if thisString = Mary, Main.js returns "undefined". If I console.log(names) it returns the array. But console.log(names[0]) is undefined. And If I copy and paste the array into the Main.js file it works as intended.

I want to have the array in another file just to clean things up a bit. But what am I doing wrong?

like image 488
John107 Avatar asked Feb 05 '19 10:02

John107


People also ask

How do you export data from JS file to another?

Implementation of Export in JavaScript Using the keyword “export” we can export anything like a variable, function, or class to any other file. What we have to do is, simply write the “export” keyword prior to that variable, function, class, or anything we want to export.

How do I copy an array part in JavaScript?

How to copy Array elements in JavaScript using concat() method. “concat()” is another useful JavaScript method that can assist you in copying array elements. In the concat() method, you can take an empty array and copy the original array elements to it. It will create a fresh copy of the specified array.

Are arrays copied by reference JS?

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable.


2 Answers

Typescript :

Array.ts

export let array = [1,2,3];

Main.ts

import {array} from "./Array.ts"
array.map(item => console.log(item +1))

Javascript (nodejs)

array.js

exports.array =  [1,2,3];

main.js

let module = require('./array.js');

let array = module.array;

array.map(item => console.log(item +1))
like image 105
Abderrahim Soubai-Elidrisi Avatar answered Oct 15 '22 09:10

Abderrahim Soubai-Elidrisi


The below works for me. You could also try:

Array.js

exports.names = [
    'John',
    'Mary'
]

Main.js

const data = require('./array.js');

const thisString = 'Mary';
if (data && data.names && data.names.includes(thisString)) {
    console.log('You are in!');
}
like image 40
Mukesh Rawat Avatar answered Oct 15 '22 07:10

Mukesh Rawat