Monday, December 4, 2023
 Popular · Latest · Hot · Upcoming
138
rated 0 times [  139] [ 1]  / answers: 1 / hits: 5126  / 4 Years ago, sun, april 26, 2020, 12:00:00

I have a directory called Polygons where I have created an index.js file to export all the files from the directory. It looks something like this:



export {default as europe} from './europe'
export {default as northAmerica} from './northAmerica'


europe file exports variable like this:



export default europe;


And in the file where I would like to use this variables I am importing them like this:



import * as regions from './Polygons'


I would like to iterate somehow now over those imports, is there any way of doing this?



I have tried doing:



  for (const element of regions) {
console.log(element);
}


But, then I get:



Uncaught (in promise) TypeError: Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

More From » es6-modules

 Answers
22

It is an object, so for..of will fail but you can use Object.keys or Object.values to convert it into array and then get the results.



Here is a sample code which is doing the same:



keys = Object.keys(React)
for (const key of keys) {
console.log(key, React[key])
}

<script src=https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js></script>





Hope it helps. Revert for any doubts/clarifications.


[#4020] Friday, April 24, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marvinm

Total Points: 406
Total Questions: 104
Total Answers: 121

Location: Iceland
Member since Tue, Jan 25, 2022
2 Years ago
marvinm questions
Sun, Dec 19, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Mon, Dec 30, 19, 00:00, 4 Years ago
;