0

What is the best way to map over array inside an array when we are importing a local file. I get an error : "Cannot read property 'map' of undefined".

Shop.js

import Details from './details.json'


render(){
 return (
   <ul>
     {Details.map(detail => (
       detail.shops.map(shop=> (
         <li>{shop}</li>
       ))
     ))}
  </ul>
 )}

Json is like this:

[
  {
    "id": 1,
    "shops": ["one", "two"]
  }
]
Deke
  • 4,451
  • 4
  • 44
  • 65
  • 2
    I believe you can't import JSON with the vanilla `import/export` syntax of ES6. You either have to use something like webpack+json-loader, or convert your JSON to a `.js` file and then import it (see this question's answer: https://stackoverflow.com/questions/34944099/how-to-import-a-json-file-in-ecmascript-6) – Jayce444 Nov 23 '18 at 19:25
  • 1
    It works as in https://codesandbox.io/s/13p1k8x2zq. But as Jayce444 said you have to use an appropriate loader for webpack(if you are using webpack), This sandbox is create-react-app based and built in config does that for in sandbox. – XPD Nov 23 '18 at 19:27
  • xpd: SyntaxError /src/index.js: Unexpected token, expected "}" (18:10) 16 |
  • {shop}
  • 17 | )) > 18 | )); | ^ – Deke Nov 23 '18 at 19:31
  • Is it the warning? – XPD Nov 23 '18 at 19:33
  • Jayce444: json loader is present for webpack 2.00 and above "Since webpack >= v2.0.0, importing of JSON files will work by default. " according to documentation – Deke Nov 23 '18 at 19:36
  • 1
    Sorry check now – XPD Nov 23 '18 at 19:36
  • XPD: your solution works now with mine. I had a '(' in my code like this: ` ( detail.shops.map` . Not sure why it threw cannot read property map and not syntax error???. – Deke Nov 23 '18 at 19:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/184161/discussion-between-xpd-and-deke). – XPD Nov 23 '18 at 19:47