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

....

1 Answer 1

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

4 Comments

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.
Because data represents an object not an array. And to traverse an object you could use Object.entries for instance, I'll update the answer with code.
Oh right! I see, object.entries isn't supported in ES2015 though right?
Nope, only in ES7. You can make it work with transform-runtime babel plugin though

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.