Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs export default of var array[] between files not treated correctly at imported scope

Tags:

I am trying to make a simple project of 2 files and I am sure I am missing a simple thing :-(

  1. zipcode.js file which contains array of Json pairs zipcode-city (see at the bottom)
  2. index.js which tries to import the array and use it.

For some reason, the import is passing but the imported array is showing error when I try to us an array function (filter), and the content of it I see when I print is empty brackets {}.

here is a shorten code versions:

zipcode.js file -

var zipcode = [
 {
   "code": 1451,
   "city": "Harvard"
 },
 {
   "code": 1503,
   "city": "Berlin"
 },
 {
   "code": 1505,
   "city": "Boylston"
 }
]

export default zipcode;

the index.js file -

import zipcode from './';
var valid_code = zipcode.filter(function(zip){
    return (zip.code === 1505);
});

error message -

var valid_code = _2.default.filter(function (zip) { ^ TypeError: _2.default.filter is not a function


What am I missing on the import procedure / concept? Thanks in advance :-)

like image 657
Gadi Ben Amram Avatar asked Jan 24 '17 23:01

Gadi Ben Amram


1 Answers

So, although this thread is almost 3 years old, for anyone who might encounter this "problem" in the future I post the hopefully correct answer. "Problem" is in quotes for good reason because this is not a real problem in itself but rather a misunderstanding which I happened to also come across:

When you write

import zipcode from './zipcode'

or

const zipcode = require('./zipcode')

then you import a module. It is and was confusing - for me as well - because the array as well as the file/module are named the same. So with your writing, you need to access the "zipcode" property of your "zipcode" module that you imported resulting in a call like this:

zipcode.zipcode.filter(...)
like image 144
Eric Wo Avatar answered Sep 22 '22 10:09

Eric Wo