0

I have another react newbie question, I am trying to load some json data from an external, local, file called intro.json But I am getting the error default.map is not a function. Any ideas on what I am doing wrong here?

My data looks like this

{
    "company": "test",
    "employees":[
    {
          "firstName":"John",
          "lastName":"Doe"
    },
    {
        "firstName":"Anna",
        "lastName":"Smith"
    }
    ]
}

I am importing like so, which I thought might work because i'm doing something similar elsewhere but not as an external file.

import React, {PropTypes} from 'react';
import data from './intro.json';

var dataList = data.map(function(dl, index) {
    return (
       <li key={index}>{dl.company}</li>
    )
});

....
Ash
  • 347
  • 3
  • 6
  • 13

1 Answers1

0

Use json-loader and the imported data will be an Object instance: Object {company: "test", employees: Array[2]} To traverse and map:

  Object.entries(data).map(([key,value])=> {
  if (Array.isArray(value)) {
    //return array value representation
    ...
  } else {
    //return normal value representation
    return (
        <div>{key} : {value}</div>
    );
  }
})
Igorsvee
  • 4,101
  • 1
  • 25
  • 21
  • Thanks but I am already using json-loader, I have it set up in my webpack config, it does not fix the issue I am having. – Ash Jul 20 '16 at 10:59
  • Because `data` represents an object not an array. And to traverse an object you could use [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) for instance, I'll update the answer with code. – Igorsvee Jul 20 '16 at 11:14
  • Oh right! I see, object.entries isn't supported in ES2015 though right? – Ash Jul 20 '16 at 13:14
  • Nope, only in ES7. You can make it work with [transform-runtime babel plugin](https://babeljs.io/docs/plugins/transform-runtime/) though – Igorsvee Jul 20 '16 at 13:42