20

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?

6
  • Where did you import names in Main.js? Commented Feb 5, 2019 at 10:18
  • What are your import/export statements? Commented Feb 5, 2019 at 10:18
  • const names = require('../array'); Commented Feb 5, 2019 at 10:21
  • @John107 Is Array.js in a folder above Main.js ? Commented Feb 5, 2019 at 10:28
  • @Leo Yes.... is that a problem? I want to access it from multiple files. Commented Feb 5, 2019 at 10:28

3 Answers 3

34

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))
Sign up to request clarification or add additional context in comments.

Comments

4

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!');
}

3 Comments

this 'should' work, but returns undefined in my application. I am unsure why.
Strange! In my solution I am assuming your array.js and main.js are in same folder, otherwise you need to modify the import path.
Yes it's very strange! I have the correct path for the array.js so I'm not sure what's going wrong.
0

Best solution for me is to export like so:

array.js

export const names = [
  'john',
  'James',
  'Jeff'
]; 

in main.js Import variable as a named-import

import { names} from './array.js'
console.log(names)

//Output => ['john', 'James', 'Jeff']

With this method you can import multiple variables from a file as long as you export them. However if you're exporting multiple variable from the same file its best to follow this convention:

export { x, y, z };
const x = 1;
const y = ['a', 'b'];
const z = {"name": "James",};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.